]> granicus.if.org Git - zfs/blob - cmd/zdb/zdb.c
ad4ebe00a65eee1ee9955ce5fe9a98e776de7637
[zfs] / cmd / zdb / zdb.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
25  * Copyright (c) 2014 Integros [integros.com]
26  * Copyright 2016 Nexenta Systems, Inc.
27  * Copyright (c) 2017, 2018 Lawrence Livermore National Security, LLC.
28  * Copyright (c) 2015, 2017, Intel Corporation.
29  */
30
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <stdio_ext.h>
34 #include <stdlib.h>
35 #include <ctype.h>
36 #include <sys/zfs_context.h>
37 #include <sys/spa.h>
38 #include <sys/spa_impl.h>
39 #include <sys/dmu.h>
40 #include <sys/zap.h>
41 #include <sys/fs/zfs.h>
42 #include <sys/zfs_znode.h>
43 #include <sys/zfs_sa.h>
44 #include <sys/sa.h>
45 #include <sys/sa_impl.h>
46 #include <sys/vdev.h>
47 #include <sys/vdev_impl.h>
48 #include <sys/metaslab_impl.h>
49 #include <sys/dmu_objset.h>
50 #include <sys/dsl_dir.h>
51 #include <sys/dsl_dataset.h>
52 #include <sys/dsl_pool.h>
53 #include <sys/dbuf.h>
54 #include <sys/zil.h>
55 #include <sys/zil_impl.h>
56 #include <sys/stat.h>
57 #include <sys/resource.h>
58 #include <sys/dmu_traverse.h>
59 #include <sys/zio_checksum.h>
60 #include <sys/zio_compress.h>
61 #include <sys/zfs_fuid.h>
62 #include <sys/arc.h>
63 #include <sys/ddt.h>
64 #include <sys/zfeature.h>
65 #include <sys/abd.h>
66 #include <sys/blkptr.h>
67 #include <sys/dsl_crypt.h>
68 #include <sys/dsl_scan.h>
69 #include <zfs_comutil.h>
70 #include <libzfs.h>
71
72 #include "zdb.h"
73
74 #define ZDB_COMPRESS_NAME(idx) ((idx) < ZIO_COMPRESS_FUNCTIONS ?        \
75         zio_compress_table[(idx)].ci_name : "UNKNOWN")
76 #define ZDB_CHECKSUM_NAME(idx) ((idx) < ZIO_CHECKSUM_FUNCTIONS ?        \
77         zio_checksum_table[(idx)].ci_name : "UNKNOWN")
78 #define ZDB_OT_TYPE(idx) ((idx) < DMU_OT_NUMTYPES ? (idx) :             \
79         (idx) == DMU_OTN_ZAP_DATA || (idx) == DMU_OTN_ZAP_METADATA ?    \
80         DMU_OT_ZAP_OTHER : \
81         (idx) == DMU_OTN_UINT64_DATA || (idx) == DMU_OTN_UINT64_METADATA ? \
82         DMU_OT_UINT64_OTHER : DMU_OT_NUMTYPES)
83
84 static char *
85 zdb_ot_name(dmu_object_type_t type)
86 {
87         if (type < DMU_OT_NUMTYPES)
88                 return (dmu_ot[type].ot_name);
89         else if ((type & DMU_OT_NEWTYPE) &&
90             ((type & DMU_OT_BYTESWAP_MASK) < DMU_BSWAP_NUMFUNCS))
91                 return (dmu_ot_byteswap[type & DMU_OT_BYTESWAP_MASK].ob_name);
92         else
93                 return ("UNKNOWN");
94 }
95
96 extern int reference_tracking_enable;
97 extern int zfs_recover;
98 extern uint64_t zfs_arc_max, zfs_arc_meta_limit;
99 extern int zfs_vdev_async_read_max_active;
100 extern boolean_t spa_load_verify_dryrun;
101
102 static const char cmdname[] = "zdb";
103 uint8_t dump_opt[256];
104
105 typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
106
107 uint64_t *zopt_object = NULL;
108 static unsigned zopt_objects = 0;
109 libzfs_handle_t *g_zfs;
110 uint64_t max_inflight = 1000;
111 static int leaked_objects = 0;
112 static range_tree_t *mos_refd_objs;
113
114 static void snprintf_blkptr_compact(char *, size_t, const blkptr_t *);
115 static void mos_obj_refd(uint64_t);
116 static void mos_obj_refd_multiple(uint64_t);
117
118 /*
119  * These libumem hooks provide a reasonable set of defaults for the allocator's
120  * debugging facilities.
121  */
122 const char *
123 _umem_debug_init(void)
124 {
125         return ("default,verbose"); /* $UMEM_DEBUG setting */
126 }
127
128 const char *
129 _umem_logging_init(void)
130 {
131         return ("fail,contents"); /* $UMEM_LOGGING setting */
132 }
133
134 static void
135 usage(void)
136 {
137         (void) fprintf(stderr,
138             "Usage:\t%s [-AbcdDFGhikLMPsvX] [-e [-V] [-p <path> ...]] "
139             "[-I <inflight I/Os>]\n"
140             "\t\t[-o <var>=<value>]... [-t <txg>] [-U <cache>] [-x <dumpdir>]\n"
141             "\t\t[<poolname> [<object> ...]]\n"
142             "\t%s [-AdiPv] [-e [-V] [-p <path> ...]] [-U <cache>] <dataset>\n"
143             "\t\t[<object> ...]\n"
144             "\t%s -C [-A] [-U <cache>]\n"
145             "\t%s -l [-Aqu] <device>\n"
146             "\t%s -m [-AFLPX] [-e [-V] [-p <path> ...]] [-t <txg>] "
147             "[-U <cache>]\n\t\t<poolname> [<vdev> [<metaslab> ...]]\n"
148             "\t%s -O <dataset> <path>\n"
149             "\t%s -R [-A] [-e [-V] [-p <path> ...]] [-U <cache>]\n"
150             "\t\t<poolname> <vdev>:<offset>:<size>[:<flags>]\n"
151             "\t%s -E [-A] word0:word1:...:word15\n"
152             "\t%s -S [-AP] [-e [-V] [-p <path> ...]] [-U <cache>] "
153             "<poolname>\n\n",
154             cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname,
155             cmdname, cmdname);
156
157         (void) fprintf(stderr, "    Dataset name must include at least one "
158             "separator character '/' or '@'\n");
159         (void) fprintf(stderr, "    If dataset name is specified, only that "
160             "dataset is dumped\n");
161         (void) fprintf(stderr, "    If object numbers are specified, only "
162             "those objects are dumped\n\n");
163         (void) fprintf(stderr, "    Options to control amount of output:\n");
164         (void) fprintf(stderr, "        -b block statistics\n");
165         (void) fprintf(stderr, "        -c checksum all metadata (twice for "
166             "all data) blocks\n");
167         (void) fprintf(stderr, "        -C config (or cachefile if alone)\n");
168         (void) fprintf(stderr, "        -d dataset(s)\n");
169         (void) fprintf(stderr, "        -D dedup statistics\n");
170         (void) fprintf(stderr, "        -E decode and display block from an "
171             "embedded block pointer\n");
172         (void) fprintf(stderr, "        -h pool history\n");
173         (void) fprintf(stderr, "        -i intent logs\n");
174         (void) fprintf(stderr, "        -l read label contents\n");
175         (void) fprintf(stderr, "        -k examine the checkpointed state "
176             "of the pool\n");
177         (void) fprintf(stderr, "        -L disable leak tracking (do not "
178             "load spacemaps)\n");
179         (void) fprintf(stderr, "        -m metaslabs\n");
180         (void) fprintf(stderr, "        -M metaslab groups\n");
181         (void) fprintf(stderr, "        -O perform object lookups by path\n");
182         (void) fprintf(stderr, "        -R read and display block from a "
183             "device\n");
184         (void) fprintf(stderr, "        -s report stats on zdb's I/O\n");
185         (void) fprintf(stderr, "        -S simulate dedup to measure effect\n");
186         (void) fprintf(stderr, "        -v verbose (applies to all "
187             "others)\n\n");
188         (void) fprintf(stderr, "    Below options are intended for use "
189             "with other options:\n");
190         (void) fprintf(stderr, "        -A ignore assertions (-A), enable "
191             "panic recovery (-AA) or both (-AAA)\n");
192         (void) fprintf(stderr, "        -e pool is exported/destroyed/"
193             "has altroot/not in a cachefile\n");
194         (void) fprintf(stderr, "        -F attempt automatic rewind within "
195             "safe range of transaction groups\n");
196         (void) fprintf(stderr, "        -G dump zfs_dbgmsg buffer before "
197             "exiting\n");
198         (void) fprintf(stderr, "        -I <number of inflight I/Os> -- "
199             "specify the maximum number of\n           "
200             "checksumming I/Os [default is 200]\n");
201         (void) fprintf(stderr, "        -o <variable>=<value> set global "
202             "variable to an unsigned 32-bit integer\n");
203         (void) fprintf(stderr, "        -p <path> -- use one or more with "
204             "-e to specify path to vdev dir\n");
205         (void) fprintf(stderr, "        -P print numbers in parseable form\n");
206         (void) fprintf(stderr, "        -q don't print label contents\n");
207         (void) fprintf(stderr, "        -t <txg> -- highest txg to use when "
208             "searching for uberblocks\n");
209         (void) fprintf(stderr, "        -u uberblock\n");
210         (void) fprintf(stderr, "        -U <cachefile_path> -- use alternate "
211             "cachefile\n");
212         (void) fprintf(stderr, "        -V do verbatim import\n");
213         (void) fprintf(stderr, "        -x <dumpdir> -- "
214             "dump all read blocks into specified directory\n");
215         (void) fprintf(stderr, "        -X attempt extreme rewind (does not "
216             "work with dataset)\n");
217         (void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
218             "to make only that option verbose\n");
219         (void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
220         exit(1);
221 }
222
223 static void
224 dump_debug_buffer(void)
225 {
226         if (dump_opt['G']) {
227                 (void) printf("\n");
228                 zfs_dbgmsg_print("zdb");
229         }
230 }
231
232 /*
233  * Called for usage errors that are discovered after a call to spa_open(),
234  * dmu_bonus_hold(), or pool_match().  abort() is called for other errors.
235  */
236
237 static void
238 fatal(const char *fmt, ...)
239 {
240         va_list ap;
241
242         va_start(ap, fmt);
243         (void) fprintf(stderr, "%s: ", cmdname);
244         (void) vfprintf(stderr, fmt, ap);
245         va_end(ap);
246         (void) fprintf(stderr, "\n");
247
248         dump_debug_buffer();
249
250         exit(1);
251 }
252
253 /* ARGSUSED */
254 static void
255 dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
256 {
257         nvlist_t *nv;
258         size_t nvsize = *(uint64_t *)data;
259         char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
260
261         VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
262
263         VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
264
265         umem_free(packed, nvsize);
266
267         dump_nvlist(nv, 8);
268
269         nvlist_free(nv);
270 }
271
272 /* ARGSUSED */
273 static void
274 dump_history_offsets(objset_t *os, uint64_t object, void *data, size_t size)
275 {
276         spa_history_phys_t *shp = data;
277
278         if (shp == NULL)
279                 return;
280
281         (void) printf("\t\tpool_create_len = %llu\n",
282             (u_longlong_t)shp->sh_pool_create_len);
283         (void) printf("\t\tphys_max_off = %llu\n",
284             (u_longlong_t)shp->sh_phys_max_off);
285         (void) printf("\t\tbof = %llu\n",
286             (u_longlong_t)shp->sh_bof);
287         (void) printf("\t\teof = %llu\n",
288             (u_longlong_t)shp->sh_eof);
289         (void) printf("\t\trecords_lost = %llu\n",
290             (u_longlong_t)shp->sh_records_lost);
291 }
292
293 static void
294 zdb_nicenum(uint64_t num, char *buf, size_t buflen)
295 {
296         if (dump_opt['P'])
297                 (void) snprintf(buf, buflen, "%llu", (longlong_t)num);
298         else
299                 nicenum(num, buf, sizeof (buf));
300 }
301
302 static const char histo_stars[] = "****************************************";
303 static const uint64_t histo_width = sizeof (histo_stars) - 1;
304
305 static void
306 dump_histogram(const uint64_t *histo, int size, int offset)
307 {
308         int i;
309         int minidx = size - 1;
310         int maxidx = 0;
311         uint64_t max = 0;
312
313         for (i = 0; i < size; i++) {
314                 if (histo[i] > max)
315                         max = histo[i];
316                 if (histo[i] > 0 && i > maxidx)
317                         maxidx = i;
318                 if (histo[i] > 0 && i < minidx)
319                         minidx = i;
320         }
321
322         if (max < histo_width)
323                 max = histo_width;
324
325         for (i = minidx; i <= maxidx; i++) {
326                 (void) printf("\t\t\t%3u: %6llu %s\n",
327                     i + offset, (u_longlong_t)histo[i],
328                     &histo_stars[(max - histo[i]) * histo_width / max]);
329         }
330 }
331
332 static void
333 dump_zap_stats(objset_t *os, uint64_t object)
334 {
335         int error;
336         zap_stats_t zs;
337
338         error = zap_get_stats(os, object, &zs);
339         if (error)
340                 return;
341
342         if (zs.zs_ptrtbl_len == 0) {
343                 ASSERT(zs.zs_num_blocks == 1);
344                 (void) printf("\tmicrozap: %llu bytes, %llu entries\n",
345                     (u_longlong_t)zs.zs_blocksize,
346                     (u_longlong_t)zs.zs_num_entries);
347                 return;
348         }
349
350         (void) printf("\tFat ZAP stats:\n");
351
352         (void) printf("\t\tPointer table:\n");
353         (void) printf("\t\t\t%llu elements\n",
354             (u_longlong_t)zs.zs_ptrtbl_len);
355         (void) printf("\t\t\tzt_blk: %llu\n",
356             (u_longlong_t)zs.zs_ptrtbl_zt_blk);
357         (void) printf("\t\t\tzt_numblks: %llu\n",
358             (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
359         (void) printf("\t\t\tzt_shift: %llu\n",
360             (u_longlong_t)zs.zs_ptrtbl_zt_shift);
361         (void) printf("\t\t\tzt_blks_copied: %llu\n",
362             (u_longlong_t)zs.zs_ptrtbl_blks_copied);
363         (void) printf("\t\t\tzt_nextblk: %llu\n",
364             (u_longlong_t)zs.zs_ptrtbl_nextblk);
365
366         (void) printf("\t\tZAP entries: %llu\n",
367             (u_longlong_t)zs.zs_num_entries);
368         (void) printf("\t\tLeaf blocks: %llu\n",
369             (u_longlong_t)zs.zs_num_leafs);
370         (void) printf("\t\tTotal blocks: %llu\n",
371             (u_longlong_t)zs.zs_num_blocks);
372         (void) printf("\t\tzap_block_type: 0x%llx\n",
373             (u_longlong_t)zs.zs_block_type);
374         (void) printf("\t\tzap_magic: 0x%llx\n",
375             (u_longlong_t)zs.zs_magic);
376         (void) printf("\t\tzap_salt: 0x%llx\n",
377             (u_longlong_t)zs.zs_salt);
378
379         (void) printf("\t\tLeafs with 2^n pointers:\n");
380         dump_histogram(zs.zs_leafs_with_2n_pointers, ZAP_HISTOGRAM_SIZE, 0);
381
382         (void) printf("\t\tBlocks with n*5 entries:\n");
383         dump_histogram(zs.zs_blocks_with_n5_entries, ZAP_HISTOGRAM_SIZE, 0);
384
385         (void) printf("\t\tBlocks n/10 full:\n");
386         dump_histogram(zs.zs_blocks_n_tenths_full, ZAP_HISTOGRAM_SIZE, 0);
387
388         (void) printf("\t\tEntries with n chunks:\n");
389         dump_histogram(zs.zs_entries_using_n_chunks, ZAP_HISTOGRAM_SIZE, 0);
390
391         (void) printf("\t\tBuckets with n entries:\n");
392         dump_histogram(zs.zs_buckets_with_n_entries, ZAP_HISTOGRAM_SIZE, 0);
393 }
394
395 /*ARGSUSED*/
396 static void
397 dump_none(objset_t *os, uint64_t object, void *data, size_t size)
398 {
399 }
400
401 /*ARGSUSED*/
402 static void
403 dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
404 {
405         (void) printf("\tUNKNOWN OBJECT TYPE\n");
406 }
407
408 /*ARGSUSED*/
409 static void
410 dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
411 {
412 }
413
414 /*ARGSUSED*/
415 static void
416 dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
417 {
418 }
419
420 /*ARGSUSED*/
421 static void
422 dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
423 {
424         zap_cursor_t zc;
425         zap_attribute_t attr;
426         void *prop;
427         unsigned i;
428
429         dump_zap_stats(os, object);
430         (void) printf("\n");
431
432         for (zap_cursor_init(&zc, os, object);
433             zap_cursor_retrieve(&zc, &attr) == 0;
434             zap_cursor_advance(&zc)) {
435                 (void) printf("\t\t%s = ", attr.za_name);
436                 if (attr.za_num_integers == 0) {
437                         (void) printf("\n");
438                         continue;
439                 }
440                 prop = umem_zalloc(attr.za_num_integers *
441                     attr.za_integer_length, UMEM_NOFAIL);
442                 (void) zap_lookup(os, object, attr.za_name,
443                     attr.za_integer_length, attr.za_num_integers, prop);
444                 if (attr.za_integer_length == 1) {
445                         (void) printf("%s", (char *)prop);
446                 } else {
447                         for (i = 0; i < attr.za_num_integers; i++) {
448                                 switch (attr.za_integer_length) {
449                                 case 2:
450                                         (void) printf("%u ",
451                                             ((uint16_t *)prop)[i]);
452                                         break;
453                                 case 4:
454                                         (void) printf("%u ",
455                                             ((uint32_t *)prop)[i]);
456                                         break;
457                                 case 8:
458                                         (void) printf("%lld ",
459                                             (u_longlong_t)((int64_t *)prop)[i]);
460                                         break;
461                                 }
462                         }
463                 }
464                 (void) printf("\n");
465                 umem_free(prop, attr.za_num_integers * attr.za_integer_length);
466         }
467         zap_cursor_fini(&zc);
468 }
469
470 static void
471 dump_bpobj(objset_t *os, uint64_t object, void *data, size_t size)
472 {
473         bpobj_phys_t *bpop = data;
474         uint64_t i;
475         char bytes[32], comp[32], uncomp[32];
476
477         /* make sure the output won't get truncated */
478         CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
479         CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
480         CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
481
482         if (bpop == NULL)
483                 return;
484
485         zdb_nicenum(bpop->bpo_bytes, bytes, sizeof (bytes));
486         zdb_nicenum(bpop->bpo_comp, comp, sizeof (comp));
487         zdb_nicenum(bpop->bpo_uncomp, uncomp, sizeof (uncomp));
488
489         (void) printf("\t\tnum_blkptrs = %llu\n",
490             (u_longlong_t)bpop->bpo_num_blkptrs);
491         (void) printf("\t\tbytes = %s\n", bytes);
492         if (size >= BPOBJ_SIZE_V1) {
493                 (void) printf("\t\tcomp = %s\n", comp);
494                 (void) printf("\t\tuncomp = %s\n", uncomp);
495         }
496         if (size >= sizeof (*bpop)) {
497                 (void) printf("\t\tsubobjs = %llu\n",
498                     (u_longlong_t)bpop->bpo_subobjs);
499                 (void) printf("\t\tnum_subobjs = %llu\n",
500                     (u_longlong_t)bpop->bpo_num_subobjs);
501         }
502
503         if (dump_opt['d'] < 5)
504                 return;
505
506         for (i = 0; i < bpop->bpo_num_blkptrs; i++) {
507                 char blkbuf[BP_SPRINTF_LEN];
508                 blkptr_t bp;
509
510                 int err = dmu_read(os, object,
511                     i * sizeof (bp), sizeof (bp), &bp, 0);
512                 if (err != 0) {
513                         (void) printf("got error %u from dmu_read\n", err);
514                         break;
515                 }
516                 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), &bp);
517                 (void) printf("\t%s\n", blkbuf);
518         }
519 }
520
521 /* ARGSUSED */
522 static void
523 dump_bpobj_subobjs(objset_t *os, uint64_t object, void *data, size_t size)
524 {
525         dmu_object_info_t doi;
526         int64_t i;
527
528         VERIFY0(dmu_object_info(os, object, &doi));
529         uint64_t *subobjs = kmem_alloc(doi.doi_max_offset, KM_SLEEP);
530
531         int err = dmu_read(os, object, 0, doi.doi_max_offset, subobjs, 0);
532         if (err != 0) {
533                 (void) printf("got error %u from dmu_read\n", err);
534                 kmem_free(subobjs, doi.doi_max_offset);
535                 return;
536         }
537
538         int64_t last_nonzero = -1;
539         for (i = 0; i < doi.doi_max_offset / 8; i++) {
540                 if (subobjs[i] != 0)
541                         last_nonzero = i;
542         }
543
544         for (i = 0; i <= last_nonzero; i++) {
545                 (void) printf("\t%llu\n", (u_longlong_t)subobjs[i]);
546         }
547         kmem_free(subobjs, doi.doi_max_offset);
548 }
549
550 /*ARGSUSED*/
551 static void
552 dump_ddt_zap(objset_t *os, uint64_t object, void *data, size_t size)
553 {
554         dump_zap_stats(os, object);
555         /* contents are printed elsewhere, properly decoded */
556 }
557
558 /*ARGSUSED*/
559 static void
560 dump_sa_attrs(objset_t *os, uint64_t object, void *data, size_t size)
561 {
562         zap_cursor_t zc;
563         zap_attribute_t attr;
564
565         dump_zap_stats(os, object);
566         (void) printf("\n");
567
568         for (zap_cursor_init(&zc, os, object);
569             zap_cursor_retrieve(&zc, &attr) == 0;
570             zap_cursor_advance(&zc)) {
571                 (void) printf("\t\t%s = ", attr.za_name);
572                 if (attr.za_num_integers == 0) {
573                         (void) printf("\n");
574                         continue;
575                 }
576                 (void) printf(" %llx : [%d:%d:%d]\n",
577                     (u_longlong_t)attr.za_first_integer,
578                     (int)ATTR_LENGTH(attr.za_first_integer),
579                     (int)ATTR_BSWAP(attr.za_first_integer),
580                     (int)ATTR_NUM(attr.za_first_integer));
581         }
582         zap_cursor_fini(&zc);
583 }
584
585 /*ARGSUSED*/
586 static void
587 dump_sa_layouts(objset_t *os, uint64_t object, void *data, size_t size)
588 {
589         zap_cursor_t zc;
590         zap_attribute_t attr;
591         uint16_t *layout_attrs;
592         unsigned i;
593
594         dump_zap_stats(os, object);
595         (void) printf("\n");
596
597         for (zap_cursor_init(&zc, os, object);
598             zap_cursor_retrieve(&zc, &attr) == 0;
599             zap_cursor_advance(&zc)) {
600                 (void) printf("\t\t%s = [", attr.za_name);
601                 if (attr.za_num_integers == 0) {
602                         (void) printf("\n");
603                         continue;
604                 }
605
606                 VERIFY(attr.za_integer_length == 2);
607                 layout_attrs = umem_zalloc(attr.za_num_integers *
608                     attr.za_integer_length, UMEM_NOFAIL);
609
610                 VERIFY(zap_lookup(os, object, attr.za_name,
611                     attr.za_integer_length,
612                     attr.za_num_integers, layout_attrs) == 0);
613
614                 for (i = 0; i != attr.za_num_integers; i++)
615                         (void) printf(" %d ", (int)layout_attrs[i]);
616                 (void) printf("]\n");
617                 umem_free(layout_attrs,
618                     attr.za_num_integers * attr.za_integer_length);
619         }
620         zap_cursor_fini(&zc);
621 }
622
623 /*ARGSUSED*/
624 static void
625 dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
626 {
627         zap_cursor_t zc;
628         zap_attribute_t attr;
629         const char *typenames[] = {
630                 /* 0 */ "not specified",
631                 /* 1 */ "FIFO",
632                 /* 2 */ "Character Device",
633                 /* 3 */ "3 (invalid)",
634                 /* 4 */ "Directory",
635                 /* 5 */ "5 (invalid)",
636                 /* 6 */ "Block Device",
637                 /* 7 */ "7 (invalid)",
638                 /* 8 */ "Regular File",
639                 /* 9 */ "9 (invalid)",
640                 /* 10 */ "Symbolic Link",
641                 /* 11 */ "11 (invalid)",
642                 /* 12 */ "Socket",
643                 /* 13 */ "Door",
644                 /* 14 */ "Event Port",
645                 /* 15 */ "15 (invalid)",
646         };
647
648         dump_zap_stats(os, object);
649         (void) printf("\n");
650
651         for (zap_cursor_init(&zc, os, object);
652             zap_cursor_retrieve(&zc, &attr) == 0;
653             zap_cursor_advance(&zc)) {
654                 (void) printf("\t\t%s = %lld (type: %s)\n",
655                     attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
656                     typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
657         }
658         zap_cursor_fini(&zc);
659 }
660
661 static int
662 get_dtl_refcount(vdev_t *vd)
663 {
664         int refcount = 0;
665
666         if (vd->vdev_ops->vdev_op_leaf) {
667                 space_map_t *sm = vd->vdev_dtl_sm;
668
669                 if (sm != NULL &&
670                     sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
671                         return (1);
672                 return (0);
673         }
674
675         for (unsigned c = 0; c < vd->vdev_children; c++)
676                 refcount += get_dtl_refcount(vd->vdev_child[c]);
677         return (refcount);
678 }
679
680 static int
681 get_metaslab_refcount(vdev_t *vd)
682 {
683         int refcount = 0;
684
685         if (vd->vdev_top == vd) {
686                 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
687                         space_map_t *sm = vd->vdev_ms[m]->ms_sm;
688
689                         if (sm != NULL &&
690                             sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
691                                 refcount++;
692                 }
693         }
694         for (unsigned c = 0; c < vd->vdev_children; c++)
695                 refcount += get_metaslab_refcount(vd->vdev_child[c]);
696
697         return (refcount);
698 }
699
700 static int
701 get_obsolete_refcount(vdev_t *vd)
702 {
703         uint64_t obsolete_sm_object;
704         int refcount = 0;
705
706         VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
707         if (vd->vdev_top == vd && obsolete_sm_object != 0) {
708                 dmu_object_info_t doi;
709                 VERIFY0(dmu_object_info(vd->vdev_spa->spa_meta_objset,
710                     obsolete_sm_object, &doi));
711                 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
712                         refcount++;
713                 }
714         } else {
715                 ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
716                 ASSERT3U(obsolete_sm_object, ==, 0);
717         }
718         for (unsigned c = 0; c < vd->vdev_children; c++) {
719                 refcount += get_obsolete_refcount(vd->vdev_child[c]);
720         }
721
722         return (refcount);
723 }
724
725 static int
726 get_prev_obsolete_spacemap_refcount(spa_t *spa)
727 {
728         uint64_t prev_obj =
729             spa->spa_condensing_indirect_phys.scip_prev_obsolete_sm_object;
730         if (prev_obj != 0) {
731                 dmu_object_info_t doi;
732                 VERIFY0(dmu_object_info(spa->spa_meta_objset, prev_obj, &doi));
733                 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
734                         return (1);
735                 }
736         }
737         return (0);
738 }
739
740 static int
741 get_checkpoint_refcount(vdev_t *vd)
742 {
743         int refcount = 0;
744
745         if (vd->vdev_top == vd && vd->vdev_top_zap != 0 &&
746             zap_contains(spa_meta_objset(vd->vdev_spa),
747             vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) == 0)
748                 refcount++;
749
750         for (uint64_t c = 0; c < vd->vdev_children; c++)
751                 refcount += get_checkpoint_refcount(vd->vdev_child[c]);
752
753         return (refcount);
754 }
755
756 static int
757 verify_spacemap_refcounts(spa_t *spa)
758 {
759         uint64_t expected_refcount = 0;
760         uint64_t actual_refcount;
761
762         (void) feature_get_refcount(spa,
763             &spa_feature_table[SPA_FEATURE_SPACEMAP_HISTOGRAM],
764             &expected_refcount);
765         actual_refcount = get_dtl_refcount(spa->spa_root_vdev);
766         actual_refcount += get_metaslab_refcount(spa->spa_root_vdev);
767         actual_refcount += get_obsolete_refcount(spa->spa_root_vdev);
768         actual_refcount += get_prev_obsolete_spacemap_refcount(spa);
769         actual_refcount += get_checkpoint_refcount(spa->spa_root_vdev);
770
771         if (expected_refcount != actual_refcount) {
772                 (void) printf("space map refcount mismatch: expected %lld != "
773                     "actual %lld\n",
774                     (longlong_t)expected_refcount,
775                     (longlong_t)actual_refcount);
776                 return (2);
777         }
778         return (0);
779 }
780
781 static void
782 dump_spacemap(objset_t *os, space_map_t *sm)
783 {
784         const char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
785             "INVALID", "INVALID", "INVALID", "INVALID" };
786
787         if (sm == NULL)
788                 return;
789
790         (void) printf("space map object %llu:\n",
791             (longlong_t)sm->sm_phys->smp_object);
792         (void) printf("  smp_objsize = 0x%llx\n",
793             (longlong_t)sm->sm_phys->smp_objsize);
794         (void) printf("  smp_alloc = 0x%llx\n",
795             (longlong_t)sm->sm_phys->smp_alloc);
796
797         /*
798          * Print out the freelist entries in both encoded and decoded form.
799          */
800         uint8_t mapshift = sm->sm_shift;
801         int64_t alloc = 0;
802         uint64_t word;
803         for (uint64_t offset = 0; offset < space_map_length(sm);
804             offset += sizeof (word)) {
805
806                 VERIFY0(dmu_read(os, space_map_object(sm), offset,
807                     sizeof (word), &word, DMU_READ_PREFETCH));
808
809                 if (sm_entry_is_debug(word)) {
810                         (void) printf("\t    [%6llu] %s: txg %llu, pass %llu\n",
811                             (u_longlong_t)(offset / sizeof (word)),
812                             ddata[SM_DEBUG_ACTION_DECODE(word)],
813                             (u_longlong_t)SM_DEBUG_TXG_DECODE(word),
814                             (u_longlong_t)SM_DEBUG_SYNCPASS_DECODE(word));
815                         continue;
816                 }
817
818                 uint8_t words;
819                 char entry_type;
820                 uint64_t entry_off, entry_run, entry_vdev = SM_NO_VDEVID;
821
822                 if (sm_entry_is_single_word(word)) {
823                         entry_type = (SM_TYPE_DECODE(word) == SM_ALLOC) ?
824                             'A' : 'F';
825                         entry_off = (SM_OFFSET_DECODE(word) << mapshift) +
826                             sm->sm_start;
827                         entry_run = SM_RUN_DECODE(word) << mapshift;
828                         words = 1;
829                 } else {
830                         /* it is a two-word entry so we read another word */
831                         ASSERT(sm_entry_is_double_word(word));
832
833                         uint64_t extra_word;
834                         offset += sizeof (extra_word);
835                         VERIFY0(dmu_read(os, space_map_object(sm), offset,
836                             sizeof (extra_word), &extra_word,
837                             DMU_READ_PREFETCH));
838
839                         ASSERT3U(offset, <=, space_map_length(sm));
840
841                         entry_run = SM2_RUN_DECODE(word) << mapshift;
842                         entry_vdev = SM2_VDEV_DECODE(word);
843                         entry_type = (SM2_TYPE_DECODE(extra_word) == SM_ALLOC) ?
844                             'A' : 'F';
845                         entry_off = (SM2_OFFSET_DECODE(extra_word) <<
846                             mapshift) + sm->sm_start;
847                         words = 2;
848                 }
849
850                 (void) printf("\t    [%6llu]    %c  range:"
851                     " %010llx-%010llx  size: %06llx vdev: %06llu words: %u\n",
852                     (u_longlong_t)(offset / sizeof (word)),
853                     entry_type, (u_longlong_t)entry_off,
854                     (u_longlong_t)(entry_off + entry_run),
855                     (u_longlong_t)entry_run,
856                     (u_longlong_t)entry_vdev, words);
857
858                 if (entry_type == 'A')
859                         alloc += entry_run;
860                 else
861                         alloc -= entry_run;
862         }
863         if ((uint64_t)alloc != space_map_allocated(sm)) {
864                 (void) printf("space_map_object alloc (%lld) INCONSISTENT "
865                     "with space map summary (%lld)\n",
866                     (longlong_t)space_map_allocated(sm), (longlong_t)alloc);
867         }
868 }
869
870 static void
871 dump_metaslab_stats(metaslab_t *msp)
872 {
873         char maxbuf[32];
874         range_tree_t *rt = msp->ms_allocatable;
875         avl_tree_t *t = &msp->ms_allocatable_by_size;
876         int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
877
878         /* max sure nicenum has enough space */
879         CTASSERT(sizeof (maxbuf) >= NN_NUMBUF_SZ);
880
881         zdb_nicenum(metaslab_block_maxsize(msp), maxbuf, sizeof (maxbuf));
882
883         (void) printf("\t %25s %10lu   %7s  %6s   %4s %4d%%\n",
884             "segments", avl_numnodes(t), "maxsize", maxbuf,
885             "freepct", free_pct);
886         (void) printf("\tIn-memory histogram:\n");
887         dump_histogram(rt->rt_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
888 }
889
890 static void
891 dump_metaslab(metaslab_t *msp)
892 {
893         vdev_t *vd = msp->ms_group->mg_vd;
894         spa_t *spa = vd->vdev_spa;
895         space_map_t *sm = msp->ms_sm;
896         char freebuf[32];
897
898         zdb_nicenum(msp->ms_size - space_map_allocated(sm), freebuf,
899             sizeof (freebuf));
900
901         (void) printf(
902             "\tmetaslab %6llu   offset %12llx   spacemap %6llu   free    %5s\n",
903             (u_longlong_t)msp->ms_id, (u_longlong_t)msp->ms_start,
904             (u_longlong_t)space_map_object(sm), freebuf);
905
906         if (dump_opt['m'] > 2 && !dump_opt['L']) {
907                 mutex_enter(&msp->ms_lock);
908                 metaslab_load_wait(msp);
909                 if (!msp->ms_loaded) {
910                         VERIFY0(metaslab_load(msp));
911                         range_tree_stat_verify(msp->ms_allocatable);
912                 }
913                 dump_metaslab_stats(msp);
914                 metaslab_unload(msp);
915                 mutex_exit(&msp->ms_lock);
916         }
917
918         if (dump_opt['m'] > 1 && sm != NULL &&
919             spa_feature_is_active(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
920                 /*
921                  * The space map histogram represents free space in chunks
922                  * of sm_shift (i.e. bucket 0 refers to 2^sm_shift).
923                  */
924                 (void) printf("\tOn-disk histogram:\t\tfragmentation %llu\n",
925                     (u_longlong_t)msp->ms_fragmentation);
926                 dump_histogram(sm->sm_phys->smp_histogram,
927                     SPACE_MAP_HISTOGRAM_SIZE, sm->sm_shift);
928         }
929
930         if (dump_opt['d'] > 5 || dump_opt['m'] > 3) {
931                 ASSERT(msp->ms_size == (1ULL << vd->vdev_ms_shift));
932
933                 dump_spacemap(spa->spa_meta_objset, msp->ms_sm);
934         }
935 }
936
937 static void
938 print_vdev_metaslab_header(vdev_t *vd)
939 {
940         vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
941         const char *bias_str;
942
943         bias_str = (alloc_bias == VDEV_BIAS_LOG || vd->vdev_islog) ?
944             VDEV_ALLOC_BIAS_LOG :
945             (alloc_bias == VDEV_BIAS_SPECIAL) ? VDEV_ALLOC_BIAS_SPECIAL :
946             (alloc_bias == VDEV_BIAS_DEDUP) ? VDEV_ALLOC_BIAS_DEDUP :
947             vd->vdev_islog ? "log" : "";
948
949         (void) printf("\tvdev %10llu   %s\n"
950             "\t%-10s%5llu   %-19s   %-15s   %-12s\n",
951             (u_longlong_t)vd->vdev_id, bias_str,
952             "metaslabs", (u_longlong_t)vd->vdev_ms_count,
953             "offset", "spacemap", "free");
954         (void) printf("\t%15s   %19s   %15s   %12s\n",
955             "---------------", "-------------------",
956             "---------------", "------------");
957 }
958
959 static void
960 dump_metaslab_groups(spa_t *spa)
961 {
962         vdev_t *rvd = spa->spa_root_vdev;
963         metaslab_class_t *mc = spa_normal_class(spa);
964         uint64_t fragmentation;
965
966         metaslab_class_histogram_verify(mc);
967
968         for (unsigned c = 0; c < rvd->vdev_children; c++) {
969                 vdev_t *tvd = rvd->vdev_child[c];
970                 metaslab_group_t *mg = tvd->vdev_mg;
971
972                 if (mg == NULL || mg->mg_class != mc)
973                         continue;
974
975                 metaslab_group_histogram_verify(mg);
976                 mg->mg_fragmentation = metaslab_group_fragmentation(mg);
977
978                 (void) printf("\tvdev %10llu\t\tmetaslabs%5llu\t\t"
979                     "fragmentation",
980                     (u_longlong_t)tvd->vdev_id,
981                     (u_longlong_t)tvd->vdev_ms_count);
982                 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
983                         (void) printf("%3s\n", "-");
984                 } else {
985                         (void) printf("%3llu%%\n",
986                             (u_longlong_t)mg->mg_fragmentation);
987                 }
988                 dump_histogram(mg->mg_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
989         }
990
991         (void) printf("\tpool %s\tfragmentation", spa_name(spa));
992         fragmentation = metaslab_class_fragmentation(mc);
993         if (fragmentation == ZFS_FRAG_INVALID)
994                 (void) printf("\t%3s\n", "-");
995         else
996                 (void) printf("\t%3llu%%\n", (u_longlong_t)fragmentation);
997         dump_histogram(mc->mc_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
998 }
999
1000 static void
1001 print_vdev_indirect(vdev_t *vd)
1002 {
1003         vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
1004         vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
1005         vdev_indirect_births_t *vib = vd->vdev_indirect_births;
1006
1007         if (vim == NULL) {
1008                 ASSERT3P(vib, ==, NULL);
1009                 return;
1010         }
1011
1012         ASSERT3U(vdev_indirect_mapping_object(vim), ==,
1013             vic->vic_mapping_object);
1014         ASSERT3U(vdev_indirect_births_object(vib), ==,
1015             vic->vic_births_object);
1016
1017         (void) printf("indirect births obj %llu:\n",
1018             (longlong_t)vic->vic_births_object);
1019         (void) printf("    vib_count = %llu\n",
1020             (longlong_t)vdev_indirect_births_count(vib));
1021         for (uint64_t i = 0; i < vdev_indirect_births_count(vib); i++) {
1022                 vdev_indirect_birth_entry_phys_t *cur_vibe =
1023                     &vib->vib_entries[i];
1024                 (void) printf("\toffset %llx -> txg %llu\n",
1025                     (longlong_t)cur_vibe->vibe_offset,
1026                     (longlong_t)cur_vibe->vibe_phys_birth_txg);
1027         }
1028         (void) printf("\n");
1029
1030         (void) printf("indirect mapping obj %llu:\n",
1031             (longlong_t)vic->vic_mapping_object);
1032         (void) printf("    vim_max_offset = 0x%llx\n",
1033             (longlong_t)vdev_indirect_mapping_max_offset(vim));
1034         (void) printf("    vim_bytes_mapped = 0x%llx\n",
1035             (longlong_t)vdev_indirect_mapping_bytes_mapped(vim));
1036         (void) printf("    vim_count = %llu\n",
1037             (longlong_t)vdev_indirect_mapping_num_entries(vim));
1038
1039         if (dump_opt['d'] <= 5 && dump_opt['m'] <= 3)
1040                 return;
1041
1042         uint32_t *counts = vdev_indirect_mapping_load_obsolete_counts(vim);
1043
1044         for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
1045                 vdev_indirect_mapping_entry_phys_t *vimep =
1046                     &vim->vim_entries[i];
1047                 (void) printf("\t<%llx:%llx:%llx> -> "
1048                     "<%llx:%llx:%llx> (%x obsolete)\n",
1049                     (longlong_t)vd->vdev_id,
1050                     (longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
1051                     (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1052                     (longlong_t)DVA_GET_VDEV(&vimep->vimep_dst),
1053                     (longlong_t)DVA_GET_OFFSET(&vimep->vimep_dst),
1054                     (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1055                     counts[i]);
1056         }
1057         (void) printf("\n");
1058
1059         uint64_t obsolete_sm_object;
1060         VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
1061         if (obsolete_sm_object != 0) {
1062                 objset_t *mos = vd->vdev_spa->spa_meta_objset;
1063                 (void) printf("obsolete space map object %llu:\n",
1064                     (u_longlong_t)obsolete_sm_object);
1065                 ASSERT(vd->vdev_obsolete_sm != NULL);
1066                 ASSERT3U(space_map_object(vd->vdev_obsolete_sm), ==,
1067                     obsolete_sm_object);
1068                 dump_spacemap(mos, vd->vdev_obsolete_sm);
1069                 (void) printf("\n");
1070         }
1071 }
1072
1073 static void
1074 dump_metaslabs(spa_t *spa)
1075 {
1076         vdev_t *vd, *rvd = spa->spa_root_vdev;
1077         uint64_t m, c = 0, children = rvd->vdev_children;
1078
1079         (void) printf("\nMetaslabs:\n");
1080
1081         if (!dump_opt['d'] && zopt_objects > 0) {
1082                 c = zopt_object[0];
1083
1084                 if (c >= children)
1085                         (void) fatal("bad vdev id: %llu", (u_longlong_t)c);
1086
1087                 if (zopt_objects > 1) {
1088                         vd = rvd->vdev_child[c];
1089                         print_vdev_metaslab_header(vd);
1090
1091                         for (m = 1; m < zopt_objects; m++) {
1092                                 if (zopt_object[m] < vd->vdev_ms_count)
1093                                         dump_metaslab(
1094                                             vd->vdev_ms[zopt_object[m]]);
1095                                 else
1096                                         (void) fprintf(stderr, "bad metaslab "
1097                                             "number %llu\n",
1098                                             (u_longlong_t)zopt_object[m]);
1099                         }
1100                         (void) printf("\n");
1101                         return;
1102                 }
1103                 children = c + 1;
1104         }
1105         for (; c < children; c++) {
1106                 vd = rvd->vdev_child[c];
1107                 print_vdev_metaslab_header(vd);
1108
1109                 print_vdev_indirect(vd);
1110
1111                 for (m = 0; m < vd->vdev_ms_count; m++)
1112                         dump_metaslab(vd->vdev_ms[m]);
1113                 (void) printf("\n");
1114         }
1115 }
1116
1117 static void
1118 dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
1119 {
1120         const ddt_phys_t *ddp = dde->dde_phys;
1121         const ddt_key_t *ddk = &dde->dde_key;
1122         const char *types[4] = { "ditto", "single", "double", "triple" };
1123         char blkbuf[BP_SPRINTF_LEN];
1124         blkptr_t blk;
1125         int p;
1126
1127         for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1128                 if (ddp->ddp_phys_birth == 0)
1129                         continue;
1130                 ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
1131                 snprintf_blkptr(blkbuf, sizeof (blkbuf), &blk);
1132                 (void) printf("index %llx refcnt %llu %s %s\n",
1133                     (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
1134                     types[p], blkbuf);
1135         }
1136 }
1137
1138 static void
1139 dump_dedup_ratio(const ddt_stat_t *dds)
1140 {
1141         double rL, rP, rD, D, dedup, compress, copies;
1142
1143         if (dds->dds_blocks == 0)
1144                 return;
1145
1146         rL = (double)dds->dds_ref_lsize;
1147         rP = (double)dds->dds_ref_psize;
1148         rD = (double)dds->dds_ref_dsize;
1149         D = (double)dds->dds_dsize;
1150
1151         dedup = rD / D;
1152         compress = rL / rP;
1153         copies = rD / rP;
1154
1155         (void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
1156             "dedup * compress / copies = %.2f\n\n",
1157             dedup, compress, copies, dedup * compress / copies);
1158 }
1159
1160 static void
1161 dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
1162 {
1163         char name[DDT_NAMELEN];
1164         ddt_entry_t dde;
1165         uint64_t walk = 0;
1166         dmu_object_info_t doi;
1167         uint64_t count, dspace, mspace;
1168         int error;
1169
1170         error = ddt_object_info(ddt, type, class, &doi);
1171
1172         if (error == ENOENT)
1173                 return;
1174         ASSERT(error == 0);
1175
1176         error = ddt_object_count(ddt, type, class, &count);
1177         ASSERT(error == 0);
1178         if (count == 0)
1179                 return;
1180
1181         dspace = doi.doi_physical_blocks_512 << 9;
1182         mspace = doi.doi_fill_count * doi.doi_data_block_size;
1183
1184         ddt_object_name(ddt, type, class, name);
1185
1186         (void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
1187             name,
1188             (u_longlong_t)count,
1189             (u_longlong_t)(dspace / count),
1190             (u_longlong_t)(mspace / count));
1191
1192         if (dump_opt['D'] < 3)
1193                 return;
1194
1195         zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
1196
1197         if (dump_opt['D'] < 4)
1198                 return;
1199
1200         if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
1201                 return;
1202
1203         (void) printf("%s contents:\n\n", name);
1204
1205         while ((error = ddt_object_walk(ddt, type, class, &walk, &dde)) == 0)
1206                 dump_dde(ddt, &dde, walk);
1207
1208         ASSERT3U(error, ==, ENOENT);
1209
1210         (void) printf("\n");
1211 }
1212
1213 static void
1214 dump_all_ddts(spa_t *spa)
1215 {
1216         ddt_histogram_t ddh_total;
1217         ddt_stat_t dds_total;
1218
1219         bzero(&ddh_total, sizeof (ddh_total));
1220         bzero(&dds_total, sizeof (dds_total));
1221
1222         for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1223                 ddt_t *ddt = spa->spa_ddt[c];
1224                 for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
1225                         for (enum ddt_class class = 0; class < DDT_CLASSES;
1226                             class++) {
1227                                 dump_ddt(ddt, type, class);
1228                         }
1229                 }
1230         }
1231
1232         ddt_get_dedup_stats(spa, &dds_total);
1233
1234         if (dds_total.dds_blocks == 0) {
1235                 (void) printf("All DDTs are empty\n");
1236                 return;
1237         }
1238
1239         (void) printf("\n");
1240
1241         if (dump_opt['D'] > 1) {
1242                 (void) printf("DDT histogram (aggregated over all DDTs):\n");
1243                 ddt_get_dedup_histogram(spa, &ddh_total);
1244                 zpool_dump_ddt(&dds_total, &ddh_total);
1245         }
1246
1247         dump_dedup_ratio(&dds_total);
1248 }
1249
1250 static void
1251 dump_dtl_seg(void *arg, uint64_t start, uint64_t size)
1252 {
1253         char *prefix = arg;
1254
1255         (void) printf("%s [%llu,%llu) length %llu\n",
1256             prefix,
1257             (u_longlong_t)start,
1258             (u_longlong_t)(start + size),
1259             (u_longlong_t)(size));
1260 }
1261
1262 static void
1263 dump_dtl(vdev_t *vd, int indent)
1264 {
1265         spa_t *spa = vd->vdev_spa;
1266         boolean_t required;
1267         const char *name[DTL_TYPES] = { "missing", "partial", "scrub",
1268                 "outage" };
1269         char prefix[256];
1270
1271         spa_vdev_state_enter(spa, SCL_NONE);
1272         required = vdev_dtl_required(vd);
1273         (void) spa_vdev_state_exit(spa, NULL, 0);
1274
1275         if (indent == 0)
1276                 (void) printf("\nDirty time logs:\n\n");
1277
1278         (void) printf("\t%*s%s [%s]\n", indent, "",
1279             vd->vdev_path ? vd->vdev_path :
1280             vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
1281             required ? "DTL-required" : "DTL-expendable");
1282
1283         for (int t = 0; t < DTL_TYPES; t++) {
1284                 range_tree_t *rt = vd->vdev_dtl[t];
1285                 if (range_tree_space(rt) == 0)
1286                         continue;
1287                 (void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
1288                     indent + 2, "", name[t]);
1289                 range_tree_walk(rt, dump_dtl_seg, prefix);
1290                 if (dump_opt['d'] > 5 && vd->vdev_children == 0)
1291                         dump_spacemap(spa->spa_meta_objset,
1292                             vd->vdev_dtl_sm);
1293         }
1294
1295         for (unsigned c = 0; c < vd->vdev_children; c++)
1296                 dump_dtl(vd->vdev_child[c], indent + 4);
1297 }
1298
1299 static void
1300 dump_history(spa_t *spa)
1301 {
1302         nvlist_t **events = NULL;
1303         char *buf;
1304         uint64_t resid, len, off = 0;
1305         uint_t num = 0;
1306         int error;
1307         time_t tsec;
1308         struct tm t;
1309         char tbuf[30];
1310         char internalstr[MAXPATHLEN];
1311
1312         if ((buf = malloc(SPA_OLD_MAXBLOCKSIZE)) == NULL) {
1313                 (void) fprintf(stderr, "%s: unable to allocate I/O buffer\n",
1314                     __func__);
1315                 return;
1316         }
1317
1318         do {
1319                 len = SPA_OLD_MAXBLOCKSIZE;
1320
1321                 if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
1322                         (void) fprintf(stderr, "Unable to read history: "
1323                             "error %d\n", error);
1324                         free(buf);
1325                         return;
1326                 }
1327
1328                 if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
1329                         break;
1330
1331                 off -= resid;
1332         } while (len != 0);
1333
1334         (void) printf("\nHistory:\n");
1335         for (unsigned i = 0; i < num; i++) {
1336                 uint64_t time, txg, ievent;
1337                 char *cmd, *intstr;
1338                 boolean_t printed = B_FALSE;
1339
1340                 if (nvlist_lookup_uint64(events[i], ZPOOL_HIST_TIME,
1341                     &time) != 0)
1342                         goto next;
1343                 if (nvlist_lookup_string(events[i], ZPOOL_HIST_CMD,
1344                     &cmd) != 0) {
1345                         if (nvlist_lookup_uint64(events[i],
1346                             ZPOOL_HIST_INT_EVENT, &ievent) != 0)
1347                                 goto next;
1348                         verify(nvlist_lookup_uint64(events[i],
1349                             ZPOOL_HIST_TXG, &txg) == 0);
1350                         verify(nvlist_lookup_string(events[i],
1351                             ZPOOL_HIST_INT_STR, &intstr) == 0);
1352                         if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
1353                                 goto next;
1354
1355                         (void) snprintf(internalstr,
1356                             sizeof (internalstr),
1357                             "[internal %s txg:%lld] %s",
1358                             zfs_history_event_names[ievent],
1359                             (longlong_t)txg, intstr);
1360                         cmd = internalstr;
1361                 }
1362                 tsec = time;
1363                 (void) localtime_r(&tsec, &t);
1364                 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
1365                 (void) printf("%s %s\n", tbuf, cmd);
1366                 printed = B_TRUE;
1367
1368 next:
1369                 if (dump_opt['h'] > 1) {
1370                         if (!printed)
1371                                 (void) printf("unrecognized record:\n");
1372                         dump_nvlist(events[i], 2);
1373                 }
1374         }
1375         free(buf);
1376 }
1377
1378 /*ARGSUSED*/
1379 static void
1380 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
1381 {
1382 }
1383
1384 static uint64_t
1385 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp,
1386     const zbookmark_phys_t *zb)
1387 {
1388         if (dnp == NULL) {
1389                 ASSERT(zb->zb_level < 0);
1390                 if (zb->zb_object == 0)
1391                         return (zb->zb_blkid);
1392                 return (zb->zb_blkid * BP_GET_LSIZE(bp));
1393         }
1394
1395         ASSERT(zb->zb_level >= 0);
1396
1397         return ((zb->zb_blkid <<
1398             (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
1399             dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
1400 }
1401
1402 static void
1403 snprintf_blkptr_compact(char *blkbuf, size_t buflen, const blkptr_t *bp)
1404 {
1405         const dva_t *dva = bp->blk_dva;
1406         int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
1407         int i;
1408
1409         if (dump_opt['b'] >= 6) {
1410                 snprintf_blkptr(blkbuf, buflen, bp);
1411                 return;
1412         }
1413
1414         if (BP_IS_EMBEDDED(bp)) {
1415                 (void) sprintf(blkbuf,
1416                     "EMBEDDED et=%u %llxL/%llxP B=%llu",
1417                     (int)BPE_GET_ETYPE(bp),
1418                     (u_longlong_t)BPE_GET_LSIZE(bp),
1419                     (u_longlong_t)BPE_GET_PSIZE(bp),
1420                     (u_longlong_t)bp->blk_birth);
1421                 return;
1422         }
1423
1424         blkbuf[0] = '\0';
1425
1426         for (i = 0; i < ndvas; i++)
1427                 (void) snprintf(blkbuf + strlen(blkbuf),
1428                     buflen - strlen(blkbuf), "%llu:%llx:%llx ",
1429                     (u_longlong_t)DVA_GET_VDEV(&dva[i]),
1430                     (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
1431                     (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
1432
1433         if (BP_IS_HOLE(bp)) {
1434                 (void) snprintf(blkbuf + strlen(blkbuf),
1435                     buflen - strlen(blkbuf),
1436                     "%llxL B=%llu",
1437                     (u_longlong_t)BP_GET_LSIZE(bp),
1438                     (u_longlong_t)bp->blk_birth);
1439         } else {
1440                 (void) snprintf(blkbuf + strlen(blkbuf),
1441                     buflen - strlen(blkbuf),
1442                     "%llxL/%llxP F=%llu B=%llu/%llu",
1443                     (u_longlong_t)BP_GET_LSIZE(bp),
1444                     (u_longlong_t)BP_GET_PSIZE(bp),
1445                     (u_longlong_t)BP_GET_FILL(bp),
1446                     (u_longlong_t)bp->blk_birth,
1447                     (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
1448         }
1449 }
1450
1451 static void
1452 print_indirect(blkptr_t *bp, const zbookmark_phys_t *zb,
1453     const dnode_phys_t *dnp)
1454 {
1455         char blkbuf[BP_SPRINTF_LEN];
1456         int l;
1457
1458         if (!BP_IS_EMBEDDED(bp)) {
1459                 ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
1460                 ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
1461         }
1462
1463         (void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
1464
1465         ASSERT(zb->zb_level >= 0);
1466
1467         for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
1468                 if (l == zb->zb_level) {
1469                         (void) printf("L%llx", (u_longlong_t)zb->zb_level);
1470                 } else {
1471                         (void) printf(" ");
1472                 }
1473         }
1474
1475         snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1476         (void) printf("%s\n", blkbuf);
1477 }
1478
1479 static int
1480 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
1481     blkptr_t *bp, const zbookmark_phys_t *zb)
1482 {
1483         int err = 0;
1484
1485         if (bp->blk_birth == 0)
1486                 return (0);
1487
1488         print_indirect(bp, zb, dnp);
1489
1490         if (BP_GET_LEVEL(bp) > 0 && !BP_IS_HOLE(bp)) {
1491                 arc_flags_t flags = ARC_FLAG_WAIT;
1492                 int i;
1493                 blkptr_t *cbp;
1494                 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
1495                 arc_buf_t *buf;
1496                 uint64_t fill = 0;
1497
1498                 err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
1499                     ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
1500                 if (err)
1501                         return (err);
1502                 ASSERT(buf->b_data);
1503
1504                 /* recursively visit blocks below this */
1505                 cbp = buf->b_data;
1506                 for (i = 0; i < epb; i++, cbp++) {
1507                         zbookmark_phys_t czb;
1508
1509                         SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1510                             zb->zb_level - 1,
1511                             zb->zb_blkid * epb + i);
1512                         err = visit_indirect(spa, dnp, cbp, &czb);
1513                         if (err)
1514                                 break;
1515                         fill += BP_GET_FILL(cbp);
1516                 }
1517                 if (!err)
1518                         ASSERT3U(fill, ==, BP_GET_FILL(bp));
1519                 arc_buf_destroy(buf, &buf);
1520         }
1521
1522         return (err);
1523 }
1524
1525 /*ARGSUSED*/
1526 static void
1527 dump_indirect(dnode_t *dn)
1528 {
1529         dnode_phys_t *dnp = dn->dn_phys;
1530         int j;
1531         zbookmark_phys_t czb;
1532
1533         (void) printf("Indirect blocks:\n");
1534
1535         SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
1536             dn->dn_object, dnp->dn_nlevels - 1, 0);
1537         for (j = 0; j < dnp->dn_nblkptr; j++) {
1538                 czb.zb_blkid = j;
1539                 (void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
1540                     &dnp->dn_blkptr[j], &czb);
1541         }
1542
1543         (void) printf("\n");
1544 }
1545
1546 /*ARGSUSED*/
1547 static void
1548 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
1549 {
1550         dsl_dir_phys_t *dd = data;
1551         time_t crtime;
1552         char nice[32];
1553
1554         /* make sure nicenum has enough space */
1555         CTASSERT(sizeof (nice) >= NN_NUMBUF_SZ);
1556
1557         if (dd == NULL)
1558                 return;
1559
1560         ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
1561
1562         crtime = dd->dd_creation_time;
1563         (void) printf("\t\tcreation_time = %s", ctime(&crtime));
1564         (void) printf("\t\thead_dataset_obj = %llu\n",
1565             (u_longlong_t)dd->dd_head_dataset_obj);
1566         (void) printf("\t\tparent_dir_obj = %llu\n",
1567             (u_longlong_t)dd->dd_parent_obj);
1568         (void) printf("\t\torigin_obj = %llu\n",
1569             (u_longlong_t)dd->dd_origin_obj);
1570         (void) printf("\t\tchild_dir_zapobj = %llu\n",
1571             (u_longlong_t)dd->dd_child_dir_zapobj);
1572         zdb_nicenum(dd->dd_used_bytes, nice, sizeof (nice));
1573         (void) printf("\t\tused_bytes = %s\n", nice);
1574         zdb_nicenum(dd->dd_compressed_bytes, nice, sizeof (nice));
1575         (void) printf("\t\tcompressed_bytes = %s\n", nice);
1576         zdb_nicenum(dd->dd_uncompressed_bytes, nice, sizeof (nice));
1577         (void) printf("\t\tuncompressed_bytes = %s\n", nice);
1578         zdb_nicenum(dd->dd_quota, nice, sizeof (nice));
1579         (void) printf("\t\tquota = %s\n", nice);
1580         zdb_nicenum(dd->dd_reserved, nice, sizeof (nice));
1581         (void) printf("\t\treserved = %s\n", nice);
1582         (void) printf("\t\tprops_zapobj = %llu\n",
1583             (u_longlong_t)dd->dd_props_zapobj);
1584         (void) printf("\t\tdeleg_zapobj = %llu\n",
1585             (u_longlong_t)dd->dd_deleg_zapobj);
1586         (void) printf("\t\tflags = %llx\n",
1587             (u_longlong_t)dd->dd_flags);
1588
1589 #define DO(which) \
1590         zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice, \
1591             sizeof (nice)); \
1592         (void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
1593         DO(HEAD);
1594         DO(SNAP);
1595         DO(CHILD);
1596         DO(CHILD_RSRV);
1597         DO(REFRSRV);
1598 #undef DO
1599         (void) printf("\t\tclones = %llu\n",
1600             (u_longlong_t)dd->dd_clones);
1601 }
1602
1603 /*ARGSUSED*/
1604 static void
1605 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
1606 {
1607         dsl_dataset_phys_t *ds = data;
1608         time_t crtime;
1609         char used[32], compressed[32], uncompressed[32], unique[32];
1610         char blkbuf[BP_SPRINTF_LEN];
1611
1612         /* make sure nicenum has enough space */
1613         CTASSERT(sizeof (used) >= NN_NUMBUF_SZ);
1614         CTASSERT(sizeof (compressed) >= NN_NUMBUF_SZ);
1615         CTASSERT(sizeof (uncompressed) >= NN_NUMBUF_SZ);
1616         CTASSERT(sizeof (unique) >= NN_NUMBUF_SZ);
1617
1618         if (ds == NULL)
1619                 return;
1620
1621         ASSERT(size == sizeof (*ds));
1622         crtime = ds->ds_creation_time;
1623         zdb_nicenum(ds->ds_referenced_bytes, used, sizeof (used));
1624         zdb_nicenum(ds->ds_compressed_bytes, compressed, sizeof (compressed));
1625         zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed,
1626             sizeof (uncompressed));
1627         zdb_nicenum(ds->ds_unique_bytes, unique, sizeof (unique));
1628         snprintf_blkptr(blkbuf, sizeof (blkbuf), &ds->ds_bp);
1629
1630         (void) printf("\t\tdir_obj = %llu\n",
1631             (u_longlong_t)ds->ds_dir_obj);
1632         (void) printf("\t\tprev_snap_obj = %llu\n",
1633             (u_longlong_t)ds->ds_prev_snap_obj);
1634         (void) printf("\t\tprev_snap_txg = %llu\n",
1635             (u_longlong_t)ds->ds_prev_snap_txg);
1636         (void) printf("\t\tnext_snap_obj = %llu\n",
1637             (u_longlong_t)ds->ds_next_snap_obj);
1638         (void) printf("\t\tsnapnames_zapobj = %llu\n",
1639             (u_longlong_t)ds->ds_snapnames_zapobj);
1640         (void) printf("\t\tnum_children = %llu\n",
1641             (u_longlong_t)ds->ds_num_children);
1642         (void) printf("\t\tuserrefs_obj = %llu\n",
1643             (u_longlong_t)ds->ds_userrefs_obj);
1644         (void) printf("\t\tcreation_time = %s", ctime(&crtime));
1645         (void) printf("\t\tcreation_txg = %llu\n",
1646             (u_longlong_t)ds->ds_creation_txg);
1647         (void) printf("\t\tdeadlist_obj = %llu\n",
1648             (u_longlong_t)ds->ds_deadlist_obj);
1649         (void) printf("\t\tused_bytes = %s\n", used);
1650         (void) printf("\t\tcompressed_bytes = %s\n", compressed);
1651         (void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
1652         (void) printf("\t\tunique = %s\n", unique);
1653         (void) printf("\t\tfsid_guid = %llu\n",
1654             (u_longlong_t)ds->ds_fsid_guid);
1655         (void) printf("\t\tguid = %llu\n",
1656             (u_longlong_t)ds->ds_guid);
1657         (void) printf("\t\tflags = %llx\n",
1658             (u_longlong_t)ds->ds_flags);
1659         (void) printf("\t\tnext_clones_obj = %llu\n",
1660             (u_longlong_t)ds->ds_next_clones_obj);
1661         (void) printf("\t\tprops_obj = %llu\n",
1662             (u_longlong_t)ds->ds_props_obj);
1663         (void) printf("\t\tbp = %s\n", blkbuf);
1664 }
1665
1666 /* ARGSUSED */
1667 static int
1668 dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1669 {
1670         char blkbuf[BP_SPRINTF_LEN];
1671
1672         if (bp->blk_birth != 0) {
1673                 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
1674                 (void) printf("\t%s\n", blkbuf);
1675         }
1676         return (0);
1677 }
1678
1679 static void
1680 dump_bptree(objset_t *os, uint64_t obj, const char *name)
1681 {
1682         char bytes[32];
1683         bptree_phys_t *bt;
1684         dmu_buf_t *db;
1685
1686         /* make sure nicenum has enough space */
1687         CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1688
1689         if (dump_opt['d'] < 3)
1690                 return;
1691
1692         VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
1693         bt = db->db_data;
1694         zdb_nicenum(bt->bt_bytes, bytes, sizeof (bytes));
1695         (void) printf("\n    %s: %llu datasets, %s\n",
1696             name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
1697         dmu_buf_rele(db, FTAG);
1698
1699         if (dump_opt['d'] < 5)
1700                 return;
1701
1702         (void) printf("\n");
1703
1704         (void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
1705 }
1706
1707 /* ARGSUSED */
1708 static int
1709 dump_bpobj_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1710 {
1711         char blkbuf[BP_SPRINTF_LEN];
1712
1713         ASSERT(bp->blk_birth != 0);
1714         snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1715         (void) printf("\t%s\n", blkbuf);
1716         return (0);
1717 }
1718
1719 static void
1720 dump_full_bpobj(bpobj_t *bpo, const char *name, int indent)
1721 {
1722         char bytes[32];
1723         char comp[32];
1724         char uncomp[32];
1725         uint64_t i;
1726
1727         /* make sure nicenum has enough space */
1728         CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1729         CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1730         CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1731
1732         if (dump_opt['d'] < 3)
1733                 return;
1734
1735         zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes, sizeof (bytes));
1736         if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1737                 zdb_nicenum(bpo->bpo_phys->bpo_comp, comp, sizeof (comp));
1738                 zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp, sizeof (uncomp));
1739                 (void) printf("    %*s: object %llu, %llu local blkptrs, "
1740                     "%llu subobjs in object, %llu, %s (%s/%s comp)\n",
1741                     indent * 8, name,
1742                     (u_longlong_t)bpo->bpo_object,
1743                     (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1744                     (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
1745                     (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
1746                     bytes, comp, uncomp);
1747
1748                 for (i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1749                         uint64_t subobj;
1750                         bpobj_t subbpo;
1751                         int error;
1752                         VERIFY0(dmu_read(bpo->bpo_os,
1753                             bpo->bpo_phys->bpo_subobjs,
1754                             i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1755                         error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1756                         if (error != 0) {
1757                                 (void) printf("ERROR %u while trying to open "
1758                                     "subobj id %llu\n",
1759                                     error, (u_longlong_t)subobj);
1760                                 continue;
1761                         }
1762                         dump_full_bpobj(&subbpo, "subobj", indent + 1);
1763                         bpobj_close(&subbpo);
1764                 }
1765         } else {
1766                 (void) printf("    %*s: object %llu, %llu blkptrs, %s\n",
1767                     indent * 8, name,
1768                     (u_longlong_t)bpo->bpo_object,
1769                     (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1770                     bytes);
1771         }
1772
1773         if (dump_opt['d'] < 5)
1774                 return;
1775
1776
1777         if (indent == 0) {
1778                 (void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
1779                 (void) printf("\n");
1780         }
1781 }
1782
1783 static void
1784 bpobj_count_refd(bpobj_t *bpo)
1785 {
1786         mos_obj_refd(bpo->bpo_object);
1787
1788         if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1789                 mos_obj_refd(bpo->bpo_phys->bpo_subobjs);
1790                 for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1791                         uint64_t subobj;
1792                         bpobj_t subbpo;
1793                         int error;
1794                         VERIFY0(dmu_read(bpo->bpo_os,
1795                             bpo->bpo_phys->bpo_subobjs,
1796                             i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1797                         error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1798                         if (error != 0) {
1799                                 (void) printf("ERROR %u while trying to open "
1800                                     "subobj id %llu\n",
1801                                     error, (u_longlong_t)subobj);
1802                                 continue;
1803                         }
1804                         bpobj_count_refd(&subbpo);
1805                         bpobj_close(&subbpo);
1806                 }
1807         }
1808 }
1809
1810 static void
1811 dump_deadlist(dsl_deadlist_t *dl)
1812 {
1813         dsl_deadlist_entry_t *dle;
1814         uint64_t unused;
1815         char bytes[32];
1816         char comp[32];
1817         char uncomp[32];
1818         uint64_t empty_bpobj =
1819             dmu_objset_spa(dl->dl_os)->spa_dsl_pool->dp_empty_bpobj;
1820
1821         /* force the tree to be loaded */
1822         dsl_deadlist_space_range(dl, 0, UINT64_MAX, &unused, &unused, &unused);
1823
1824         if (dl->dl_oldfmt) {
1825                 if (dl->dl_bpobj.bpo_object != empty_bpobj)
1826                         bpobj_count_refd(&dl->dl_bpobj);
1827         } else {
1828                 mos_obj_refd(dl->dl_object);
1829                 for (dle = avl_first(&dl->dl_tree); dle;
1830                     dle = AVL_NEXT(&dl->dl_tree, dle)) {
1831                         if (dle->dle_bpobj.bpo_object != empty_bpobj)
1832                                 bpobj_count_refd(&dle->dle_bpobj);
1833                 }
1834         }
1835
1836         /* make sure nicenum has enough space */
1837         CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1838         CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1839         CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1840
1841         if (dump_opt['d'] < 3)
1842                 return;
1843
1844         if (dl->dl_oldfmt) {
1845                 dump_full_bpobj(&dl->dl_bpobj, "old-format deadlist", 0);
1846                 return;
1847         }
1848
1849         zdb_nicenum(dl->dl_phys->dl_used, bytes, sizeof (bytes));
1850         zdb_nicenum(dl->dl_phys->dl_comp, comp, sizeof (comp));
1851         zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp, sizeof (uncomp));
1852         (void) printf("\n    Deadlist: %s (%s/%s comp)\n",
1853             bytes, comp, uncomp);
1854
1855         if (dump_opt['d'] < 4)
1856                 return;
1857
1858         (void) printf("\n");
1859
1860         for (dle = avl_first(&dl->dl_tree); dle;
1861             dle = AVL_NEXT(&dl->dl_tree, dle)) {
1862                 if (dump_opt['d'] >= 5) {
1863                         char buf[128];
1864                         (void) snprintf(buf, sizeof (buf),
1865                             "mintxg %llu -> obj %llu",
1866                             (longlong_t)dle->dle_mintxg,
1867                             (longlong_t)dle->dle_bpobj.bpo_object);
1868
1869                         dump_full_bpobj(&dle->dle_bpobj, buf, 0);
1870                 } else {
1871                         (void) printf("mintxg %llu -> obj %llu\n",
1872                             (longlong_t)dle->dle_mintxg,
1873                             (longlong_t)dle->dle_bpobj.bpo_object);
1874                 }
1875         }
1876 }
1877
1878 static avl_tree_t idx_tree;
1879 static avl_tree_t domain_tree;
1880 static boolean_t fuid_table_loaded;
1881 static objset_t *sa_os = NULL;
1882 static sa_attr_type_t *sa_attr_table = NULL;
1883
1884 static int
1885 open_objset(const char *path, dmu_objset_type_t type, void *tag, objset_t **osp)
1886 {
1887         int err;
1888         uint64_t sa_attrs = 0;
1889         uint64_t version = 0;
1890
1891         VERIFY3P(sa_os, ==, NULL);
1892         err = dmu_objset_own(path, type, B_TRUE, B_FALSE, tag, osp);
1893         if (err != 0) {
1894                 (void) fprintf(stderr, "failed to own dataset '%s': %s\n", path,
1895                     strerror(err));
1896                 return (err);
1897         }
1898
1899         if (dmu_objset_type(*osp) == DMU_OST_ZFS && !(*osp)->os_encrypted) {
1900                 (void) zap_lookup(*osp, MASTER_NODE_OBJ, ZPL_VERSION_STR,
1901                     8, 1, &version);
1902                 if (version >= ZPL_VERSION_SA) {
1903                         (void) zap_lookup(*osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
1904                             8, 1, &sa_attrs);
1905                 }
1906                 err = sa_setup(*osp, sa_attrs, zfs_attr_table, ZPL_END,
1907                     &sa_attr_table);
1908                 if (err != 0) {
1909                         (void) fprintf(stderr, "sa_setup failed: %s\n",
1910                             strerror(err));
1911                         dmu_objset_disown(*osp, B_FALSE, tag);
1912                         *osp = NULL;
1913                 }
1914         }
1915         sa_os = *osp;
1916
1917         return (0);
1918 }
1919
1920 static void
1921 close_objset(objset_t *os, void *tag)
1922 {
1923         VERIFY3P(os, ==, sa_os);
1924         if (os->os_sa != NULL)
1925                 sa_tear_down(os);
1926         dmu_objset_disown(os, B_FALSE, tag);
1927         sa_attr_table = NULL;
1928         sa_os = NULL;
1929 }
1930
1931 static void
1932 fuid_table_destroy(void)
1933 {
1934         if (fuid_table_loaded) {
1935                 zfs_fuid_table_destroy(&idx_tree, &domain_tree);
1936                 fuid_table_loaded = B_FALSE;
1937         }
1938 }
1939
1940 /*
1941  * print uid or gid information.
1942  * For normal POSIX id just the id is printed in decimal format.
1943  * For CIFS files with FUID the fuid is printed in hex followed by
1944  * the domain-rid string.
1945  */
1946 static void
1947 print_idstr(uint64_t id, const char *id_type)
1948 {
1949         if (FUID_INDEX(id)) {
1950                 char *domain;
1951
1952                 domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
1953                 (void) printf("\t%s     %llx [%s-%d]\n", id_type,
1954                     (u_longlong_t)id, domain, (int)FUID_RID(id));
1955         } else {
1956                 (void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
1957         }
1958
1959 }
1960
1961 static void
1962 dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
1963 {
1964         uint32_t uid_idx, gid_idx;
1965
1966         uid_idx = FUID_INDEX(uid);
1967         gid_idx = FUID_INDEX(gid);
1968
1969         /* Load domain table, if not already loaded */
1970         if (!fuid_table_loaded && (uid_idx || gid_idx)) {
1971                 uint64_t fuid_obj;
1972
1973                 /* first find the fuid object.  It lives in the master node */
1974                 VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
1975                     8, 1, &fuid_obj) == 0);
1976                 zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
1977                 (void) zfs_fuid_table_load(os, fuid_obj,
1978                     &idx_tree, &domain_tree);
1979                 fuid_table_loaded = B_TRUE;
1980         }
1981
1982         print_idstr(uid, "uid");
1983         print_idstr(gid, "gid");
1984 }
1985
1986 static void
1987 dump_znode_sa_xattr(sa_handle_t *hdl)
1988 {
1989         nvlist_t *sa_xattr;
1990         nvpair_t *elem = NULL;
1991         int sa_xattr_size = 0;
1992         int sa_xattr_entries = 0;
1993         int error;
1994         char *sa_xattr_packed;
1995
1996         error = sa_size(hdl, sa_attr_table[ZPL_DXATTR], &sa_xattr_size);
1997         if (error || sa_xattr_size == 0)
1998                 return;
1999
2000         sa_xattr_packed = malloc(sa_xattr_size);
2001         if (sa_xattr_packed == NULL)
2002                 return;
2003
2004         error = sa_lookup(hdl, sa_attr_table[ZPL_DXATTR],
2005             sa_xattr_packed, sa_xattr_size);
2006         if (error) {
2007                 free(sa_xattr_packed);
2008                 return;
2009         }
2010
2011         error = nvlist_unpack(sa_xattr_packed, sa_xattr_size, &sa_xattr, 0);
2012         if (error) {
2013                 free(sa_xattr_packed);
2014                 return;
2015         }
2016
2017         while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL)
2018                 sa_xattr_entries++;
2019
2020         (void) printf("\tSA xattrs: %d bytes, %d entries\n\n",
2021             sa_xattr_size, sa_xattr_entries);
2022         while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL) {
2023                 uchar_t *value;
2024                 uint_t cnt, idx;
2025
2026                 (void) printf("\t\t%s = ", nvpair_name(elem));
2027                 nvpair_value_byte_array(elem, &value, &cnt);
2028                 for (idx = 0; idx < cnt; ++idx) {
2029                         if (isprint(value[idx]))
2030                                 (void) putchar(value[idx]);
2031                         else
2032                                 (void) printf("\\%3.3o", value[idx]);
2033                 }
2034                 (void) putchar('\n');
2035         }
2036
2037         nvlist_free(sa_xattr);
2038         free(sa_xattr_packed);
2039 }
2040
2041 /*ARGSUSED*/
2042 static void
2043 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
2044 {
2045         char path[MAXPATHLEN * 2];      /* allow for xattr and failure prefix */
2046         sa_handle_t *hdl;
2047         uint64_t xattr, rdev, gen;
2048         uint64_t uid, gid, mode, fsize, parent, links;
2049         uint64_t pflags;
2050         uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
2051         time_t z_crtime, z_atime, z_mtime, z_ctime;
2052         sa_bulk_attr_t bulk[12];
2053         int idx = 0;
2054         int error;
2055
2056         VERIFY3P(os, ==, sa_os);
2057         if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
2058                 (void) printf("Failed to get handle for SA znode\n");
2059                 return;
2060         }
2061
2062         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
2063         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
2064         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
2065             &links, 8);
2066         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
2067         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
2068             &mode, 8);
2069         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
2070             NULL, &parent, 8);
2071         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
2072             &fsize, 8);
2073         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
2074             acctm, 16);
2075         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
2076             modtm, 16);
2077         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
2078             crtm, 16);
2079         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
2080             chgtm, 16);
2081         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
2082             &pflags, 8);
2083
2084         if (sa_bulk_lookup(hdl, bulk, idx)) {
2085                 (void) sa_handle_destroy(hdl);
2086                 return;
2087         }
2088
2089         z_crtime = (time_t)crtm[0];
2090         z_atime = (time_t)acctm[0];
2091         z_mtime = (time_t)modtm[0];
2092         z_ctime = (time_t)chgtm[0];
2093
2094         if (dump_opt['d'] > 4) {
2095                 error = zfs_obj_to_path(os, object, path, sizeof (path));
2096                 if (error == ESTALE) {
2097                         (void) snprintf(path, sizeof (path), "on delete queue");
2098                 } else if (error != 0) {
2099                         leaked_objects++;
2100                         (void) snprintf(path, sizeof (path),
2101                             "path not found, possibly leaked");
2102                 }
2103                 (void) printf("\tpath   %s\n", path);
2104         }
2105         dump_uidgid(os, uid, gid);
2106         (void) printf("\tatime  %s", ctime(&z_atime));
2107         (void) printf("\tmtime  %s", ctime(&z_mtime));
2108         (void) printf("\tctime  %s", ctime(&z_ctime));
2109         (void) printf("\tcrtime %s", ctime(&z_crtime));
2110         (void) printf("\tgen    %llu\n", (u_longlong_t)gen);
2111         (void) printf("\tmode   %llo\n", (u_longlong_t)mode);
2112         (void) printf("\tsize   %llu\n", (u_longlong_t)fsize);
2113         (void) printf("\tparent %llu\n", (u_longlong_t)parent);
2114         (void) printf("\tlinks  %llu\n", (u_longlong_t)links);
2115         (void) printf("\tpflags %llx\n", (u_longlong_t)pflags);
2116         if (dmu_objset_projectquota_enabled(os) && (pflags & ZFS_PROJID)) {
2117                 uint64_t projid;
2118
2119                 if (sa_lookup(hdl, sa_attr_table[ZPL_PROJID], &projid,
2120                     sizeof (uint64_t)) == 0)
2121                         (void) printf("\tprojid %llu\n", (u_longlong_t)projid);
2122         }
2123         if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
2124             sizeof (uint64_t)) == 0)
2125                 (void) printf("\txattr  %llu\n", (u_longlong_t)xattr);
2126         if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
2127             sizeof (uint64_t)) == 0)
2128                 (void) printf("\trdev   0x%016llx\n", (u_longlong_t)rdev);
2129         dump_znode_sa_xattr(hdl);
2130         sa_handle_destroy(hdl);
2131 }
2132
2133 /*ARGSUSED*/
2134 static void
2135 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
2136 {
2137 }
2138
2139 /*ARGSUSED*/
2140 static void
2141 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
2142 {
2143 }
2144
2145 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
2146         dump_none,              /* unallocated                  */
2147         dump_zap,               /* object directory             */
2148         dump_uint64,            /* object array                 */
2149         dump_none,              /* packed nvlist                */
2150         dump_packed_nvlist,     /* packed nvlist size           */
2151         dump_none,              /* bpobj                        */
2152         dump_bpobj,             /* bpobj header                 */
2153         dump_none,              /* SPA space map header         */
2154         dump_none,              /* SPA space map                */
2155         dump_none,              /* ZIL intent log               */
2156         dump_dnode,             /* DMU dnode                    */
2157         dump_dmu_objset,        /* DMU objset                   */
2158         dump_dsl_dir,           /* DSL directory                */
2159         dump_zap,               /* DSL directory child map      */
2160         dump_zap,               /* DSL dataset snap map         */
2161         dump_zap,               /* DSL props                    */
2162         dump_dsl_dataset,       /* DSL dataset                  */
2163         dump_znode,             /* ZFS znode                    */
2164         dump_acl,               /* ZFS V0 ACL                   */
2165         dump_uint8,             /* ZFS plain file               */
2166         dump_zpldir,            /* ZFS directory                */
2167         dump_zap,               /* ZFS master node              */
2168         dump_zap,               /* ZFS delete queue             */
2169         dump_uint8,             /* zvol object                  */
2170         dump_zap,               /* zvol prop                    */
2171         dump_uint8,             /* other uint8[]                */
2172         dump_uint64,            /* other uint64[]               */
2173         dump_zap,               /* other ZAP                    */
2174         dump_zap,               /* persistent error log         */
2175         dump_uint8,             /* SPA history                  */
2176         dump_history_offsets,   /* SPA history offsets          */
2177         dump_zap,               /* Pool properties              */
2178         dump_zap,               /* DSL permissions              */
2179         dump_acl,               /* ZFS ACL                      */
2180         dump_uint8,             /* ZFS SYSACL                   */
2181         dump_none,              /* FUID nvlist                  */
2182         dump_packed_nvlist,     /* FUID nvlist size             */
2183         dump_zap,               /* DSL dataset next clones      */
2184         dump_zap,               /* DSL scrub queue              */
2185         dump_zap,               /* ZFS user/group/project used  */
2186         dump_zap,               /* ZFS user/group/project quota */
2187         dump_zap,               /* snapshot refcount tags       */
2188         dump_ddt_zap,           /* DDT ZAP object               */
2189         dump_zap,               /* DDT statistics               */
2190         dump_znode,             /* SA object                    */
2191         dump_zap,               /* SA Master Node               */
2192         dump_sa_attrs,          /* SA attribute registration    */
2193         dump_sa_layouts,        /* SA attribute layouts         */
2194         dump_zap,               /* DSL scrub translations       */
2195         dump_none,              /* fake dedup BP                */
2196         dump_zap,               /* deadlist                     */
2197         dump_none,              /* deadlist hdr                 */
2198         dump_zap,               /* dsl clones                   */
2199         dump_bpobj_subobjs,     /* bpobj subobjs                */
2200         dump_unknown,           /* Unknown type, must be last   */
2201 };
2202
2203 static void
2204 dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header,
2205     uint64_t *dnode_slots_used)
2206 {
2207         dmu_buf_t *db = NULL;
2208         dmu_object_info_t doi;
2209         dnode_t *dn;
2210         boolean_t dnode_held = B_FALSE;
2211         void *bonus = NULL;
2212         size_t bsize = 0;
2213         char iblk[32], dblk[32], lsize[32], asize[32], fill[32], dnsize[32];
2214         char bonus_size[32];
2215         char aux[50];
2216         int error;
2217
2218         /* make sure nicenum has enough space */
2219         CTASSERT(sizeof (iblk) >= NN_NUMBUF_SZ);
2220         CTASSERT(sizeof (dblk) >= NN_NUMBUF_SZ);
2221         CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
2222         CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
2223         CTASSERT(sizeof (bonus_size) >= NN_NUMBUF_SZ);
2224
2225         if (*print_header) {
2226                 (void) printf("\n%10s  %3s  %5s  %5s  %5s  %6s  %5s  %6s  %s\n",
2227                     "Object", "lvl", "iblk", "dblk", "dsize", "dnsize",
2228                     "lsize", "%full", "type");
2229                 *print_header = 0;
2230         }
2231
2232         if (object == 0) {
2233                 dn = DMU_META_DNODE(os);
2234                 dmu_object_info_from_dnode(dn, &doi);
2235         } else {
2236                 /*
2237                  * Encrypted datasets will have sensitive bonus buffers
2238                  * encrypted. Therefore we cannot hold the bonus buffer and
2239                  * must hold the dnode itself instead.
2240                  */
2241                 error = dmu_object_info(os, object, &doi);
2242                 if (error)
2243                         fatal("dmu_object_info() failed, errno %u", error);
2244
2245                 if (os->os_encrypted &&
2246                     DMU_OT_IS_ENCRYPTED(doi.doi_bonus_type)) {
2247                         error = dnode_hold(os, object, FTAG, &dn);
2248                         if (error)
2249                                 fatal("dnode_hold() failed, errno %u", error);
2250                         dnode_held = B_TRUE;
2251                 } else {
2252                         error = dmu_bonus_hold(os, object, FTAG, &db);
2253                         if (error)
2254                                 fatal("dmu_bonus_hold(%llu) failed, errno %u",
2255                                     object, error);
2256                         bonus = db->db_data;
2257                         bsize = db->db_size;
2258                         dn = DB_DNODE((dmu_buf_impl_t *)db);
2259                 }
2260         }
2261
2262         if (dnode_slots_used)
2263                 *dnode_slots_used = doi.doi_dnodesize / DNODE_MIN_SIZE;
2264
2265         zdb_nicenum(doi.doi_metadata_block_size, iblk, sizeof (iblk));
2266         zdb_nicenum(doi.doi_data_block_size, dblk, sizeof (dblk));
2267         zdb_nicenum(doi.doi_max_offset, lsize, sizeof (lsize));
2268         zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize, sizeof (asize));
2269         zdb_nicenum(doi.doi_bonus_size, bonus_size, sizeof (bonus_size));
2270         zdb_nicenum(doi.doi_dnodesize, dnsize, sizeof (dnsize));
2271         (void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
2272             doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
2273             doi.doi_max_offset);
2274
2275         aux[0] = '\0';
2276
2277         if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
2278                 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
2279                     " (K=%s)", ZDB_CHECKSUM_NAME(doi.doi_checksum));
2280         }
2281
2282         if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
2283                 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
2284                     " (Z=%s)", ZDB_COMPRESS_NAME(doi.doi_compress));
2285         }
2286
2287         (void) printf("%10lld  %3u  %5s  %5s  %5s  %6s  %5s  %6s  %s%s\n",
2288             (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
2289             asize, dnsize, lsize, fill, zdb_ot_name(doi.doi_type), aux);
2290
2291         if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
2292                 (void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %5s  %6s  %s\n",
2293                     "", "", "", "", "", "", bonus_size, "bonus",
2294                     zdb_ot_name(doi.doi_bonus_type));
2295         }
2296
2297         if (verbosity >= 4) {
2298                 (void) printf("\tdnode flags: %s%s%s%s\n",
2299                     (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
2300                     "USED_BYTES " : "",
2301                     (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
2302                     "USERUSED_ACCOUNTED " : "",
2303                     (dn->dn_phys->dn_flags & DNODE_FLAG_USEROBJUSED_ACCOUNTED) ?
2304                     "USEROBJUSED_ACCOUNTED " : "",
2305                     (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
2306                     "SPILL_BLKPTR" : "");
2307                 (void) printf("\tdnode maxblkid: %llu\n",
2308                     (longlong_t)dn->dn_phys->dn_maxblkid);
2309
2310                 if (!dnode_held) {
2311                         object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os,
2312                             object, bonus, bsize);
2313                 } else {
2314                         (void) printf("\t\t(bonus encrypted)\n");
2315                 }
2316
2317                 if (!os->os_encrypted || !DMU_OT_IS_ENCRYPTED(doi.doi_type)) {
2318                         object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object,
2319                             NULL, 0);
2320                 } else {
2321                         (void) printf("\t\t(object encrypted)\n");
2322                 }
2323
2324                 *print_header = 1;
2325         }
2326
2327         if (verbosity >= 5)
2328                 dump_indirect(dn);
2329
2330         if (verbosity >= 5) {
2331                 /*
2332                  * Report the list of segments that comprise the object.
2333                  */
2334                 uint64_t start = 0;
2335                 uint64_t end;
2336                 uint64_t blkfill = 1;
2337                 int minlvl = 1;
2338
2339                 if (dn->dn_type == DMU_OT_DNODE) {
2340                         minlvl = 0;
2341                         blkfill = DNODES_PER_BLOCK;
2342                 }
2343
2344                 for (;;) {
2345                         char segsize[32];
2346                         /* make sure nicenum has enough space */
2347                         CTASSERT(sizeof (segsize) >= NN_NUMBUF_SZ);
2348                         error = dnode_next_offset(dn,
2349                             0, &start, minlvl, blkfill, 0);
2350                         if (error)
2351                                 break;
2352                         end = start;
2353                         error = dnode_next_offset(dn,
2354                             DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
2355                         zdb_nicenum(end - start, segsize, sizeof (segsize));
2356                         (void) printf("\t\tsegment [%016llx, %016llx)"
2357                             " size %5s\n", (u_longlong_t)start,
2358                             (u_longlong_t)end, segsize);
2359                         if (error)
2360                                 break;
2361                         start = end;
2362                 }
2363         }
2364
2365         if (db != NULL)
2366                 dmu_buf_rele(db, FTAG);
2367         if (dnode_held)
2368                 dnode_rele(dn, FTAG);
2369 }
2370
2371 static void
2372 count_dir_mos_objects(dsl_dir_t *dd)
2373 {
2374         mos_obj_refd(dd->dd_object);
2375         mos_obj_refd(dsl_dir_phys(dd)->dd_child_dir_zapobj);
2376         mos_obj_refd(dsl_dir_phys(dd)->dd_deleg_zapobj);
2377         mos_obj_refd(dsl_dir_phys(dd)->dd_props_zapobj);
2378         mos_obj_refd(dsl_dir_phys(dd)->dd_clones);
2379
2380         /*
2381          * The dd_crypto_obj can be referenced by multiple dsl_dir's.
2382          * Ignore the references after the first one.
2383          */
2384         mos_obj_refd_multiple(dd->dd_crypto_obj);
2385 }
2386
2387 static void
2388 count_ds_mos_objects(dsl_dataset_t *ds)
2389 {
2390         mos_obj_refd(ds->ds_object);
2391         mos_obj_refd(dsl_dataset_phys(ds)->ds_next_clones_obj);
2392         mos_obj_refd(dsl_dataset_phys(ds)->ds_props_obj);
2393         mos_obj_refd(dsl_dataset_phys(ds)->ds_userrefs_obj);
2394         mos_obj_refd(dsl_dataset_phys(ds)->ds_snapnames_zapobj);
2395
2396         if (!dsl_dataset_is_snapshot(ds)) {
2397                 count_dir_mos_objects(ds->ds_dir);
2398         }
2399 }
2400
2401 static const char *objset_types[DMU_OST_NUMTYPES] = {
2402         "NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
2403
2404 static void
2405 dump_dir(objset_t *os)
2406 {
2407         dmu_objset_stats_t dds;
2408         uint64_t object, object_count;
2409         uint64_t refdbytes, usedobjs, scratch;
2410         char numbuf[32];
2411         char blkbuf[BP_SPRINTF_LEN + 20];
2412         char osname[ZFS_MAX_DATASET_NAME_LEN];
2413         const char *type = "UNKNOWN";
2414         int verbosity = dump_opt['d'];
2415         int print_header = 1;
2416         unsigned i;
2417         int error;
2418         uint64_t total_slots_used = 0;
2419         uint64_t max_slot_used = 0;
2420         uint64_t dnode_slots;
2421
2422         /* make sure nicenum has enough space */
2423         CTASSERT(sizeof (numbuf) >= NN_NUMBUF_SZ);
2424
2425         dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
2426         dmu_objset_fast_stat(os, &dds);
2427         dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
2428
2429         if (dds.dds_type < DMU_OST_NUMTYPES)
2430                 type = objset_types[dds.dds_type];
2431
2432         if (dds.dds_type == DMU_OST_META) {
2433                 dds.dds_creation_txg = TXG_INITIAL;
2434                 usedobjs = BP_GET_FILL(os->os_rootbp);
2435                 refdbytes = dsl_dir_phys(os->os_spa->spa_dsl_pool->dp_mos_dir)->
2436                     dd_used_bytes;
2437         } else {
2438                 dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
2439         }
2440
2441         ASSERT3U(usedobjs, ==, BP_GET_FILL(os->os_rootbp));
2442
2443         zdb_nicenum(refdbytes, numbuf, sizeof (numbuf));
2444
2445         if (verbosity >= 4) {
2446                 (void) snprintf(blkbuf, sizeof (blkbuf), ", rootbp ");
2447                 (void) snprintf_blkptr(blkbuf + strlen(blkbuf),
2448                     sizeof (blkbuf) - strlen(blkbuf), os->os_rootbp);
2449         } else {
2450                 blkbuf[0] = '\0';
2451         }
2452
2453         dmu_objset_name(os, osname);
2454
2455         (void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
2456             "%s, %llu objects%s\n",
2457             osname, type, (u_longlong_t)dmu_objset_id(os),
2458             (u_longlong_t)dds.dds_creation_txg,
2459             numbuf, (u_longlong_t)usedobjs, blkbuf);
2460
2461         if (zopt_objects != 0) {
2462                 for (i = 0; i < zopt_objects; i++)
2463                         dump_object(os, zopt_object[i], verbosity,
2464                             &print_header, NULL);
2465                 (void) printf("\n");
2466                 return;
2467         }
2468
2469         if (dump_opt['i'] != 0 || verbosity >= 2)
2470                 dump_intent_log(dmu_objset_zil(os));
2471
2472         if (dmu_objset_ds(os) != NULL) {
2473                 dsl_dataset_t *ds = dmu_objset_ds(os);
2474                 dump_deadlist(&ds->ds_deadlist);
2475
2476                 if (dsl_dataset_remap_deadlist_exists(ds)) {
2477                         (void) printf("ds_remap_deadlist:\n");
2478                         dump_deadlist(&ds->ds_remap_deadlist);
2479                 }
2480                 count_ds_mos_objects(ds);
2481         }
2482
2483         if (verbosity < 2)
2484                 return;
2485
2486         if (BP_IS_HOLE(os->os_rootbp))
2487                 return;
2488
2489         dump_object(os, 0, verbosity, &print_header, NULL);
2490         object_count = 0;
2491         if (DMU_USERUSED_DNODE(os) != NULL &&
2492             DMU_USERUSED_DNODE(os)->dn_type != 0) {
2493                 dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header,
2494                     NULL);
2495                 dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header,
2496                     NULL);
2497         }
2498
2499         if (DMU_PROJECTUSED_DNODE(os) != NULL &&
2500             DMU_PROJECTUSED_DNODE(os)->dn_type != 0)
2501                 dump_object(os, DMU_PROJECTUSED_OBJECT, verbosity,
2502                     &print_header, NULL);
2503
2504         object = 0;
2505         while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
2506                 dump_object(os, object, verbosity, &print_header, &dnode_slots);
2507                 object_count++;
2508                 total_slots_used += dnode_slots;
2509                 max_slot_used = object + dnode_slots - 1;
2510         }
2511
2512         (void) printf("\n");
2513
2514         (void) printf("    Dnode slots:\n");
2515         (void) printf("\tTotal used:    %10llu\n",
2516             (u_longlong_t)total_slots_used);
2517         (void) printf("\tMax used:      %10llu\n",
2518             (u_longlong_t)max_slot_used);
2519         (void) printf("\tPercent empty: %10lf\n",
2520             (double)(max_slot_used - total_slots_used)*100 /
2521             (double)max_slot_used);
2522
2523         ASSERT3U(object_count, ==, usedobjs);
2524
2525         (void) printf("\n");
2526
2527         if (error != ESRCH) {
2528                 (void) fprintf(stderr, "dmu_object_next() = %d\n", error);
2529                 abort();
2530         }
2531         if (leaked_objects != 0) {
2532                 (void) printf("%d potentially leaked objects detected\n",
2533                     leaked_objects);
2534                 leaked_objects = 0;
2535         }
2536 }
2537
2538 static void
2539 dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
2540 {
2541         time_t timestamp = ub->ub_timestamp;
2542
2543         (void) printf("%s", header ? header : "");
2544         (void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
2545         (void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
2546         (void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
2547         (void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
2548         (void) printf("\ttimestamp = %llu UTC = %s",
2549             (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
2550
2551         (void) printf("\tmmp_magic = %016llx\n",
2552             (u_longlong_t)ub->ub_mmp_magic);
2553         if (ub->ub_mmp_magic == MMP_MAGIC)
2554                 (void) printf("\tmmp_delay = %0llu\n",
2555                     (u_longlong_t)ub->ub_mmp_delay);
2556
2557         if (dump_opt['u'] >= 4) {
2558                 char blkbuf[BP_SPRINTF_LEN];
2559                 snprintf_blkptr(blkbuf, sizeof (blkbuf), &ub->ub_rootbp);
2560                 (void) printf("\trootbp = %s\n", blkbuf);
2561         }
2562         (void) printf("\tcheckpoint_txg = %llu\n",
2563             (u_longlong_t)ub->ub_checkpoint_txg);
2564         (void) printf("%s", footer ? footer : "");
2565 }
2566
2567 static void
2568 dump_config(spa_t *spa)
2569 {
2570         dmu_buf_t *db;
2571         size_t nvsize = 0;
2572         int error = 0;
2573
2574
2575         error = dmu_bonus_hold(spa->spa_meta_objset,
2576             spa->spa_config_object, FTAG, &db);
2577
2578         if (error == 0) {
2579                 nvsize = *(uint64_t *)db->db_data;
2580                 dmu_buf_rele(db, FTAG);
2581
2582                 (void) printf("\nMOS Configuration:\n");
2583                 dump_packed_nvlist(spa->spa_meta_objset,
2584                     spa->spa_config_object, (void *)&nvsize, 1);
2585         } else {
2586                 (void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
2587                     (u_longlong_t)spa->spa_config_object, error);
2588         }
2589 }
2590
2591 static void
2592 dump_cachefile(const char *cachefile)
2593 {
2594         int fd;
2595         struct stat64 statbuf;
2596         char *buf;
2597         nvlist_t *config;
2598
2599         if ((fd = open64(cachefile, O_RDONLY)) < 0) {
2600                 (void) printf("cannot open '%s': %s\n", cachefile,
2601                     strerror(errno));
2602                 exit(1);
2603         }
2604
2605         if (fstat64(fd, &statbuf) != 0) {
2606                 (void) printf("failed to stat '%s': %s\n", cachefile,
2607                     strerror(errno));
2608                 exit(1);
2609         }
2610
2611         if ((buf = malloc(statbuf.st_size)) == NULL) {
2612                 (void) fprintf(stderr, "failed to allocate %llu bytes\n",
2613                     (u_longlong_t)statbuf.st_size);
2614                 exit(1);
2615         }
2616
2617         if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
2618                 (void) fprintf(stderr, "failed to read %llu bytes\n",
2619                     (u_longlong_t)statbuf.st_size);
2620                 exit(1);
2621         }
2622
2623         (void) close(fd);
2624
2625         if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
2626                 (void) fprintf(stderr, "failed to unpack nvlist\n");
2627                 exit(1);
2628         }
2629
2630         free(buf);
2631
2632         dump_nvlist(config, 0);
2633
2634         nvlist_free(config);
2635 }
2636
2637 /*
2638  * ZFS label nvlist stats
2639  */
2640 typedef struct zdb_nvl_stats {
2641         int             zns_list_count;
2642         int             zns_leaf_count;
2643         size_t          zns_leaf_largest;
2644         size_t          zns_leaf_total;
2645         nvlist_t        *zns_string;
2646         nvlist_t        *zns_uint64;
2647         nvlist_t        *zns_boolean;
2648 } zdb_nvl_stats_t;
2649
2650 static void
2651 collect_nvlist_stats(nvlist_t *nvl, zdb_nvl_stats_t *stats)
2652 {
2653         nvlist_t *list, **array;
2654         nvpair_t *nvp = NULL;
2655         char *name;
2656         uint_t i, items;
2657
2658         stats->zns_list_count++;
2659
2660         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
2661                 name = nvpair_name(nvp);
2662
2663                 switch (nvpair_type(nvp)) {
2664                 case DATA_TYPE_STRING:
2665                         fnvlist_add_string(stats->zns_string, name,
2666                             fnvpair_value_string(nvp));
2667                         break;
2668                 case DATA_TYPE_UINT64:
2669                         fnvlist_add_uint64(stats->zns_uint64, name,
2670                             fnvpair_value_uint64(nvp));
2671                         break;
2672                 case DATA_TYPE_BOOLEAN:
2673                         fnvlist_add_boolean(stats->zns_boolean, name);
2674                         break;
2675                 case DATA_TYPE_NVLIST:
2676                         if (nvpair_value_nvlist(nvp, &list) == 0)
2677                                 collect_nvlist_stats(list, stats);
2678                         break;
2679                 case DATA_TYPE_NVLIST_ARRAY:
2680                         if (nvpair_value_nvlist_array(nvp, &array, &items) != 0)
2681                                 break;
2682
2683                         for (i = 0; i < items; i++) {
2684                                 collect_nvlist_stats(array[i], stats);
2685
2686                                 /* collect stats on leaf vdev */
2687                                 if (strcmp(name, "children") == 0) {
2688                                         size_t size;
2689
2690                                         (void) nvlist_size(array[i], &size,
2691                                             NV_ENCODE_XDR);
2692                                         stats->zns_leaf_total += size;
2693                                         if (size > stats->zns_leaf_largest)
2694                                                 stats->zns_leaf_largest = size;
2695                                         stats->zns_leaf_count++;
2696                                 }
2697                         }
2698                         break;
2699                 default:
2700                         (void) printf("skip type %d!\n", (int)nvpair_type(nvp));
2701                 }
2702         }
2703 }
2704
2705 static void
2706 dump_nvlist_stats(nvlist_t *nvl, size_t cap)
2707 {
2708         zdb_nvl_stats_t stats = { 0 };
2709         size_t size, sum = 0, total;
2710         size_t noise;
2711
2712         /* requires nvlist with non-unique names for stat collection */
2713         VERIFY0(nvlist_alloc(&stats.zns_string, 0, 0));
2714         VERIFY0(nvlist_alloc(&stats.zns_uint64, 0, 0));
2715         VERIFY0(nvlist_alloc(&stats.zns_boolean, 0, 0));
2716         VERIFY0(nvlist_size(stats.zns_boolean, &noise, NV_ENCODE_XDR));
2717
2718         (void) printf("\n\nZFS Label NVList Config Stats:\n");
2719
2720         VERIFY0(nvlist_size(nvl, &total, NV_ENCODE_XDR));
2721         (void) printf("  %d bytes used, %d bytes free (using %4.1f%%)\n\n",
2722             (int)total, (int)(cap - total), 100.0 * total / cap);
2723
2724         collect_nvlist_stats(nvl, &stats);
2725
2726         VERIFY0(nvlist_size(stats.zns_uint64, &size, NV_ENCODE_XDR));
2727         size -= noise;
2728         sum += size;
2729         (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "integers:",
2730             (int)fnvlist_num_pairs(stats.zns_uint64),
2731             (int)size, 100.0 * size / total);
2732
2733         VERIFY0(nvlist_size(stats.zns_string, &size, NV_ENCODE_XDR));
2734         size -= noise;
2735         sum += size;
2736         (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "strings:",
2737             (int)fnvlist_num_pairs(stats.zns_string),
2738             (int)size, 100.0 * size / total);
2739
2740         VERIFY0(nvlist_size(stats.zns_boolean, &size, NV_ENCODE_XDR));
2741         size -= noise;
2742         sum += size;
2743         (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "booleans:",
2744             (int)fnvlist_num_pairs(stats.zns_boolean),
2745             (int)size, 100.0 * size / total);
2746
2747         size = total - sum;     /* treat remainder as nvlist overhead */
2748         (void) printf("%12s %4d %6d bytes (%5.2f%%)\n\n", "nvlists:",
2749             stats.zns_list_count, (int)size, 100.0 * size / total);
2750
2751         if (stats.zns_leaf_count > 0) {
2752                 size_t average = stats.zns_leaf_total / stats.zns_leaf_count;
2753
2754                 (void) printf("%12s %4d %6d bytes average\n", "leaf vdevs:",
2755                     stats.zns_leaf_count, (int)average);
2756                 (void) printf("%24d bytes largest\n",
2757                     (int)stats.zns_leaf_largest);
2758
2759                 if (dump_opt['l'] >= 3 && average > 0)
2760                         (void) printf("  space for %d additional leaf vdevs\n",
2761                             (int)((cap - total) / average));
2762         }
2763         (void) printf("\n");
2764
2765         nvlist_free(stats.zns_string);
2766         nvlist_free(stats.zns_uint64);
2767         nvlist_free(stats.zns_boolean);
2768 }
2769
2770 typedef struct cksum_record {
2771         zio_cksum_t cksum;
2772         boolean_t labels[VDEV_LABELS];
2773         avl_node_t link;
2774 } cksum_record_t;
2775
2776 static int
2777 cksum_record_compare(const void *x1, const void *x2)
2778 {
2779         const cksum_record_t *l = (cksum_record_t *)x1;
2780         const cksum_record_t *r = (cksum_record_t *)x2;
2781         int arraysize = ARRAY_SIZE(l->cksum.zc_word);
2782         int difference;
2783
2784         for (int i = 0; i < arraysize; i++) {
2785                 difference = AVL_CMP(l->cksum.zc_word[i], r->cksum.zc_word[i]);
2786                 if (difference)
2787                         break;
2788         }
2789
2790         return (difference);
2791 }
2792
2793 static cksum_record_t *
2794 cksum_record_alloc(zio_cksum_t *cksum, int l)
2795 {
2796         cksum_record_t *rec;
2797
2798         rec = umem_zalloc(sizeof (*rec), UMEM_NOFAIL);
2799         rec->cksum = *cksum;
2800         rec->labels[l] = B_TRUE;
2801
2802         return (rec);
2803 }
2804
2805 static cksum_record_t *
2806 cksum_record_lookup(avl_tree_t *tree, zio_cksum_t *cksum)
2807 {
2808         cksum_record_t lookup = { .cksum = *cksum };
2809         avl_index_t where;
2810
2811         return (avl_find(tree, &lookup, &where));
2812 }
2813
2814 static cksum_record_t *
2815 cksum_record_insert(avl_tree_t *tree, zio_cksum_t *cksum, int l)
2816 {
2817         cksum_record_t *rec;
2818
2819         rec = cksum_record_lookup(tree, cksum);
2820         if (rec) {
2821                 rec->labels[l] = B_TRUE;
2822         } else {
2823                 rec = cksum_record_alloc(cksum, l);
2824                 avl_add(tree, rec);
2825         }
2826
2827         return (rec);
2828 }
2829
2830 static int
2831 first_label(cksum_record_t *rec)
2832 {
2833         for (int i = 0; i < VDEV_LABELS; i++)
2834                 if (rec->labels[i])
2835                         return (i);
2836
2837         return (-1);
2838 }
2839
2840 static void
2841 print_label_numbers(char *prefix, cksum_record_t *rec)
2842 {
2843         printf("%s", prefix);
2844         for (int i = 0; i < VDEV_LABELS; i++)
2845                 if (rec->labels[i] == B_TRUE)
2846                         printf("%d ", i);
2847         printf("\n");
2848 }
2849
2850 #define MAX_UBERBLOCK_COUNT (VDEV_UBERBLOCK_RING >> UBERBLOCK_SHIFT)
2851
2852 typedef struct label {
2853         vdev_label_t label;
2854         nvlist_t *config_nv;
2855         cksum_record_t *config;
2856         cksum_record_t *uberblocks[MAX_UBERBLOCK_COUNT];
2857         boolean_t header_printed;
2858         boolean_t read_failed;
2859 } label_t;
2860
2861 static void
2862 print_label_header(label_t *label, int l)
2863 {
2864
2865         if (dump_opt['q'])
2866                 return;
2867
2868         if (label->header_printed == B_TRUE)
2869                 return;
2870
2871         (void) printf("------------------------------------\n");
2872         (void) printf("LABEL %d\n", l);
2873         (void) printf("------------------------------------\n");
2874
2875         label->header_printed = B_TRUE;
2876 }
2877
2878 static void
2879 dump_config_from_label(label_t *label, size_t buflen, int l)
2880 {
2881         if (dump_opt['q'])
2882                 return;
2883
2884         if ((dump_opt['l'] < 3) && (first_label(label->config) != l))
2885                 return;
2886
2887         print_label_header(label, l);
2888         dump_nvlist(label->config_nv, 4);
2889         print_label_numbers("    labels = ", label->config);
2890
2891         if (dump_opt['l'] >= 2)
2892                 dump_nvlist_stats(label->config_nv, buflen);
2893 }
2894
2895 #define ZDB_MAX_UB_HEADER_SIZE 32
2896
2897 static void
2898 dump_label_uberblocks(label_t *label, uint64_t ashift, int label_num)
2899 {
2900
2901         vdev_t vd;
2902         char header[ZDB_MAX_UB_HEADER_SIZE];
2903
2904         vd.vdev_ashift = ashift;
2905         vd.vdev_top = &vd;
2906
2907         for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
2908                 uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
2909                 uberblock_t *ub = (void *)((char *)&label->label + uoff);
2910                 cksum_record_t *rec = label->uberblocks[i];
2911
2912                 if (rec == NULL) {
2913                         if (dump_opt['u'] >= 2) {
2914                                 print_label_header(label, label_num);
2915                                 (void) printf("    Uberblock[%d] invalid\n", i);
2916                         }
2917                         continue;
2918                 }
2919
2920                 if ((dump_opt['u'] < 3) && (first_label(rec) != label_num))
2921                         continue;
2922
2923                 if ((dump_opt['u'] < 4) &&
2924                     (ub->ub_mmp_magic == MMP_MAGIC) && ub->ub_mmp_delay &&
2925                     (i >= VDEV_UBERBLOCK_COUNT(&vd) - MMP_BLOCKS_PER_LABEL))
2926                         continue;
2927
2928                 print_label_header(label, label_num);
2929                 (void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
2930                     "    Uberblock[%d]\n", i);
2931                 dump_uberblock(ub, header, "");
2932                 print_label_numbers("        labels = ", rec);
2933         }
2934 }
2935
2936 static char curpath[PATH_MAX];
2937
2938 /*
2939  * Iterate through the path components, recursively passing
2940  * current one's obj and remaining path until we find the obj
2941  * for the last one.
2942  */
2943 static int
2944 dump_path_impl(objset_t *os, uint64_t obj, char *name)
2945 {
2946         int err;
2947         int header = 1;
2948         uint64_t child_obj;
2949         char *s;
2950         dmu_buf_t *db;
2951         dmu_object_info_t doi;
2952
2953         if ((s = strchr(name, '/')) != NULL)
2954                 *s = '\0';
2955         err = zap_lookup(os, obj, name, 8, 1, &child_obj);
2956
2957         (void) strlcat(curpath, name, sizeof (curpath));
2958
2959         if (err != 0) {
2960                 (void) fprintf(stderr, "failed to lookup %s: %s\n",
2961                     curpath, strerror(err));
2962                 return (err);
2963         }
2964
2965         child_obj = ZFS_DIRENT_OBJ(child_obj);
2966         err = sa_buf_hold(os, child_obj, FTAG, &db);
2967         if (err != 0) {
2968                 (void) fprintf(stderr,
2969                     "failed to get SA dbuf for obj %llu: %s\n",
2970                     (u_longlong_t)child_obj, strerror(err));
2971                 return (EINVAL);
2972         }
2973         dmu_object_info_from_db(db, &doi);
2974         sa_buf_rele(db, FTAG);
2975
2976         if (doi.doi_bonus_type != DMU_OT_SA &&
2977             doi.doi_bonus_type != DMU_OT_ZNODE) {
2978                 (void) fprintf(stderr, "invalid bonus type %d for obj %llu\n",
2979                     doi.doi_bonus_type, (u_longlong_t)child_obj);
2980                 return (EINVAL);
2981         }
2982
2983         if (dump_opt['v'] > 6) {
2984                 (void) printf("obj=%llu %s type=%d bonustype=%d\n",
2985                     (u_longlong_t)child_obj, curpath, doi.doi_type,
2986                     doi.doi_bonus_type);
2987         }
2988
2989         (void) strlcat(curpath, "/", sizeof (curpath));
2990
2991         switch (doi.doi_type) {
2992         case DMU_OT_DIRECTORY_CONTENTS:
2993                 if (s != NULL && *(s + 1) != '\0')
2994                         return (dump_path_impl(os, child_obj, s + 1));
2995                 /*FALLTHROUGH*/
2996         case DMU_OT_PLAIN_FILE_CONTENTS:
2997                 dump_object(os, child_obj, dump_opt['v'], &header, NULL);
2998                 return (0);
2999         default:
3000                 (void) fprintf(stderr, "object %llu has non-file/directory "
3001                     "type %d\n", (u_longlong_t)obj, doi.doi_type);
3002                 break;
3003         }
3004
3005         return (EINVAL);
3006 }
3007
3008 /*
3009  * Dump the blocks for the object specified by path inside the dataset.
3010  */
3011 static int
3012 dump_path(char *ds, char *path)
3013 {
3014         int err;
3015         objset_t *os;
3016         uint64_t root_obj;
3017
3018         err = open_objset(ds, DMU_OST_ZFS, FTAG, &os);
3019         if (err != 0)
3020                 return (err);
3021
3022         err = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1, &root_obj);
3023         if (err != 0) {
3024                 (void) fprintf(stderr, "can't lookup root znode: %s\n",
3025                     strerror(err));
3026                 dmu_objset_disown(os, B_FALSE, FTAG);
3027                 return (EINVAL);
3028         }
3029
3030         (void) snprintf(curpath, sizeof (curpath), "dataset=%s path=/", ds);
3031
3032         err = dump_path_impl(os, root_obj, path);
3033
3034         close_objset(os, FTAG);
3035         return (err);
3036 }
3037
3038 static int
3039 dump_label(const char *dev)
3040 {
3041         char path[MAXPATHLEN];
3042         label_t labels[VDEV_LABELS];
3043         uint64_t psize, ashift;
3044         struct stat64 statbuf;
3045         boolean_t config_found = B_FALSE;
3046         boolean_t error = B_FALSE;
3047         avl_tree_t config_tree;
3048         avl_tree_t uberblock_tree;
3049         void *node, *cookie;
3050         int fd;
3051
3052         bzero(labels, sizeof (labels));
3053
3054         /*
3055          * Check if we were given absolute path and use it as is.
3056          * Otherwise if the provided vdev name doesn't point to a file,
3057          * try prepending expected disk paths and partition numbers.
3058          */
3059         (void) strlcpy(path, dev, sizeof (path));
3060         if (dev[0] != '/' && stat64(path, &statbuf) != 0) {
3061                 int error;
3062
3063                 error = zfs_resolve_shortname(dev, path, MAXPATHLEN);
3064                 if (error == 0 && zfs_dev_is_whole_disk(path)) {
3065                         if (zfs_append_partition(path, MAXPATHLEN) == -1)
3066                                 error = ENOENT;
3067                 }
3068
3069                 if (error || (stat64(path, &statbuf) != 0)) {
3070                         (void) printf("failed to find device %s, try "
3071                             "specifying absolute path instead\n", dev);
3072                         return (1);
3073                 }
3074         }
3075
3076         if ((fd = open64(path, O_RDONLY)) < 0) {
3077                 (void) printf("cannot open '%s': %s\n", path, strerror(errno));
3078                 exit(1);
3079         }
3080
3081         if (fstat64_blk(fd, &statbuf) != 0) {
3082                 (void) printf("failed to stat '%s': %s\n", path,
3083                     strerror(errno));
3084                 (void) close(fd);
3085                 exit(1);
3086         }
3087
3088         if (S_ISBLK(statbuf.st_mode) && ioctl(fd, BLKFLSBUF) != 0)
3089                 (void) printf("failed to invalidate cache '%s' : %s\n", path,
3090                     strerror(errno));
3091
3092         avl_create(&config_tree, cksum_record_compare,
3093             sizeof (cksum_record_t), offsetof(cksum_record_t, link));
3094         avl_create(&uberblock_tree, cksum_record_compare,
3095             sizeof (cksum_record_t), offsetof(cksum_record_t, link));
3096
3097         psize = statbuf.st_size;
3098         psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
3099         ashift = SPA_MINBLOCKSHIFT;
3100
3101         /*
3102          * 1. Read the label from disk
3103          * 2. Unpack the configuration and insert in config tree.
3104          * 3. Traverse all uberblocks and insert in uberblock tree.
3105          */
3106         for (int l = 0; l < VDEV_LABELS; l++) {
3107                 label_t *label = &labels[l];
3108                 char *buf = label->label.vl_vdev_phys.vp_nvlist;
3109                 size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
3110                 nvlist_t *config;
3111                 cksum_record_t *rec;
3112                 zio_cksum_t cksum;
3113                 vdev_t vd;
3114
3115                 if (pread64(fd, &label->label, sizeof (label->label),
3116                     vdev_label_offset(psize, l, 0)) != sizeof (label->label)) {
3117                         if (!dump_opt['q'])
3118                                 (void) printf("failed to read label %d\n", l);
3119                         label->read_failed = B_TRUE;
3120                         error = B_TRUE;
3121                         continue;
3122                 }
3123
3124                 label->read_failed = B_FALSE;
3125
3126                 if (nvlist_unpack(buf, buflen, &config, 0) == 0) {
3127                         nvlist_t *vdev_tree = NULL;
3128                         size_t size;
3129
3130                         if ((nvlist_lookup_nvlist(config,
3131                             ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
3132                             (nvlist_lookup_uint64(vdev_tree,
3133                             ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
3134                                 ashift = SPA_MINBLOCKSHIFT;
3135
3136                         if (nvlist_size(config, &size, NV_ENCODE_XDR) != 0)
3137                                 size = buflen;
3138
3139                         fletcher_4_native_varsize(buf, size, &cksum);
3140                         rec = cksum_record_insert(&config_tree, &cksum, l);
3141
3142                         label->config = rec;
3143                         label->config_nv = config;
3144                         config_found = B_TRUE;
3145                 } else {
3146                         error = B_TRUE;
3147                 }
3148
3149                 vd.vdev_ashift = ashift;
3150                 vd.vdev_top = &vd;
3151
3152                 for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
3153                         uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
3154                         uberblock_t *ub = (void *)((char *)label + uoff);
3155
3156                         if (uberblock_verify(ub))
3157                                 continue;
3158
3159                         fletcher_4_native_varsize(ub, sizeof (*ub), &cksum);
3160                         rec = cksum_record_insert(&uberblock_tree, &cksum, l);
3161
3162                         label->uberblocks[i] = rec;
3163                 }
3164         }
3165
3166         /*
3167          * Dump the label and uberblocks.
3168          */
3169         for (int l = 0; l < VDEV_LABELS; l++) {
3170                 label_t *label = &labels[l];
3171                 size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
3172
3173                 if (label->read_failed == B_TRUE)
3174                         continue;
3175
3176                 if (label->config_nv) {
3177                         dump_config_from_label(label, buflen, l);
3178                 } else {
3179                         if (!dump_opt['q'])
3180                                 (void) printf("failed to unpack label %d\n", l);
3181                 }
3182
3183                 if (dump_opt['u'])
3184                         dump_label_uberblocks(label, ashift, l);
3185
3186                 nvlist_free(label->config_nv);
3187         }
3188
3189         cookie = NULL;
3190         while ((node = avl_destroy_nodes(&config_tree, &cookie)) != NULL)
3191                 umem_free(node, sizeof (cksum_record_t));
3192
3193         cookie = NULL;
3194         while ((node = avl_destroy_nodes(&uberblock_tree, &cookie)) != NULL)
3195                 umem_free(node, sizeof (cksum_record_t));
3196
3197         avl_destroy(&config_tree);
3198         avl_destroy(&uberblock_tree);
3199
3200         (void) close(fd);
3201
3202         return (config_found == B_FALSE ? 2 :
3203             (error == B_TRUE ? 1 : 0));
3204 }
3205
3206 static uint64_t dataset_feature_count[SPA_FEATURES];
3207 static uint64_t remap_deadlist_count = 0;
3208
3209 /*ARGSUSED*/
3210 static int
3211 dump_one_dir(const char *dsname, void *arg)
3212 {
3213         int error;
3214         objset_t *os;
3215         spa_feature_t f;
3216
3217         error = open_objset(dsname, DMU_OST_ANY, FTAG, &os);
3218         if (error != 0)
3219                 return (0);
3220
3221         for (f = 0; f < SPA_FEATURES; f++) {
3222                 if (!dsl_dataset_feature_is_active(dmu_objset_ds(os), f))
3223                         continue;
3224                 ASSERT(spa_feature_table[f].fi_flags &
3225                     ZFEATURE_FLAG_PER_DATASET);
3226                 dataset_feature_count[f]++;
3227         }
3228
3229         if (dsl_dataset_remap_deadlist_exists(dmu_objset_ds(os))) {
3230                 remap_deadlist_count++;
3231         }
3232
3233         dump_dir(os);
3234         close_objset(os, FTAG);
3235         fuid_table_destroy();
3236         return (0);
3237 }
3238
3239 /*
3240  * Block statistics.
3241  */
3242 #define PSIZE_HISTO_SIZE (SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 2)
3243 typedef struct zdb_blkstats {
3244         uint64_t zb_asize;
3245         uint64_t zb_lsize;
3246         uint64_t zb_psize;
3247         uint64_t zb_count;
3248         uint64_t zb_gangs;
3249         uint64_t zb_ditto_samevdev;
3250         uint64_t zb_ditto_same_ms;
3251         uint64_t zb_psize_histogram[PSIZE_HISTO_SIZE];
3252 } zdb_blkstats_t;
3253
3254 /*
3255  * Extended object types to report deferred frees and dedup auto-ditto blocks.
3256  */
3257 #define ZDB_OT_DEFERRED (DMU_OT_NUMTYPES + 0)
3258 #define ZDB_OT_DITTO    (DMU_OT_NUMTYPES + 1)
3259 #define ZDB_OT_OTHER    (DMU_OT_NUMTYPES + 2)
3260 #define ZDB_OT_TOTAL    (DMU_OT_NUMTYPES + 3)
3261
3262 static const char *zdb_ot_extname[] = {
3263         "deferred free",
3264         "dedup ditto",
3265         "other",
3266         "Total",
3267 };
3268
3269 #define ZB_TOTAL        DN_MAX_LEVELS
3270
3271 typedef struct zdb_cb {
3272         zdb_blkstats_t  zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
3273         uint64_t        zcb_removing_size;
3274         uint64_t        zcb_checkpoint_size;
3275         uint64_t        zcb_dedup_asize;
3276         uint64_t        zcb_dedup_blocks;
3277         uint64_t        zcb_embedded_blocks[NUM_BP_EMBEDDED_TYPES];
3278         uint64_t        zcb_embedded_histogram[NUM_BP_EMBEDDED_TYPES]
3279             [BPE_PAYLOAD_SIZE + 1];
3280         uint64_t        zcb_start;
3281         hrtime_t        zcb_lastprint;
3282         uint64_t        zcb_totalasize;
3283         uint64_t        zcb_errors[256];
3284         int             zcb_readfails;
3285         int             zcb_haderrors;
3286         spa_t           *zcb_spa;
3287         uint32_t        **zcb_vd_obsolete_counts;
3288 } zdb_cb_t;
3289
3290 /* test if two DVA offsets from same vdev are within the same metaslab */
3291 static boolean_t
3292 same_metaslab(spa_t *spa, uint64_t vdev, uint64_t off1, uint64_t off2)
3293 {
3294         vdev_t *vd = vdev_lookup_top(spa, vdev);
3295         uint64_t ms_shift = vd->vdev_ms_shift;
3296
3297         return ((off1 >> ms_shift) == (off2 >> ms_shift));
3298 }
3299
3300 static void
3301 zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
3302     dmu_object_type_t type)
3303 {
3304         uint64_t refcnt = 0;
3305         int i;
3306
3307         ASSERT(type < ZDB_OT_TOTAL);
3308
3309         if (zilog && zil_bp_tree_add(zilog, bp) != 0)
3310                 return;
3311
3312         spa_config_enter(zcb->zcb_spa, SCL_CONFIG, FTAG, RW_READER);
3313
3314         for (i = 0; i < 4; i++) {
3315                 int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
3316                 int t = (i & 1) ? type : ZDB_OT_TOTAL;
3317                 int equal;
3318                 zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
3319
3320                 zb->zb_asize += BP_GET_ASIZE(bp);
3321                 zb->zb_lsize += BP_GET_LSIZE(bp);
3322                 zb->zb_psize += BP_GET_PSIZE(bp);
3323                 zb->zb_count++;
3324
3325                 /*
3326                  * The histogram is only big enough to record blocks up to
3327                  * SPA_OLD_MAXBLOCKSIZE; larger blocks go into the last,
3328                  * "other", bucket.
3329                  */
3330                 unsigned idx = BP_GET_PSIZE(bp) >> SPA_MINBLOCKSHIFT;
3331                 idx = MIN(idx, SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 1);
3332                 zb->zb_psize_histogram[idx]++;
3333
3334                 zb->zb_gangs += BP_COUNT_GANG(bp);
3335
3336                 switch (BP_GET_NDVAS(bp)) {
3337                 case 2:
3338                         if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3339                             DVA_GET_VDEV(&bp->blk_dva[1])) {
3340                                 zb->zb_ditto_samevdev++;
3341
3342                                 if (same_metaslab(zcb->zcb_spa,
3343                                     DVA_GET_VDEV(&bp->blk_dva[0]),
3344                                     DVA_GET_OFFSET(&bp->blk_dva[0]),
3345                                     DVA_GET_OFFSET(&bp->blk_dva[1])))
3346                                         zb->zb_ditto_same_ms++;
3347                         }
3348                         break;
3349                 case 3:
3350                         equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3351                             DVA_GET_VDEV(&bp->blk_dva[1])) +
3352                             (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3353                             DVA_GET_VDEV(&bp->blk_dva[2])) +
3354                             (DVA_GET_VDEV(&bp->blk_dva[1]) ==
3355                             DVA_GET_VDEV(&bp->blk_dva[2]));
3356                         if (equal != 0) {
3357                                 zb->zb_ditto_samevdev++;
3358
3359                                 if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3360                                     DVA_GET_VDEV(&bp->blk_dva[1]) &&
3361                                     same_metaslab(zcb->zcb_spa,
3362                                     DVA_GET_VDEV(&bp->blk_dva[0]),
3363                                     DVA_GET_OFFSET(&bp->blk_dva[0]),
3364                                     DVA_GET_OFFSET(&bp->blk_dva[1])))
3365                                         zb->zb_ditto_same_ms++;
3366                                 else if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3367                                     DVA_GET_VDEV(&bp->blk_dva[2]) &&
3368                                     same_metaslab(zcb->zcb_spa,
3369                                     DVA_GET_VDEV(&bp->blk_dva[0]),
3370                                     DVA_GET_OFFSET(&bp->blk_dva[0]),
3371                                     DVA_GET_OFFSET(&bp->blk_dva[2])))
3372                                         zb->zb_ditto_same_ms++;
3373                                 else if (DVA_GET_VDEV(&bp->blk_dva[1]) ==
3374                                     DVA_GET_VDEV(&bp->blk_dva[2]) &&
3375                                     same_metaslab(zcb->zcb_spa,
3376                                     DVA_GET_VDEV(&bp->blk_dva[1]),
3377                                     DVA_GET_OFFSET(&bp->blk_dva[1]),
3378                                     DVA_GET_OFFSET(&bp->blk_dva[2])))
3379                                         zb->zb_ditto_same_ms++;
3380                         }
3381                         break;
3382                 }
3383         }
3384
3385         spa_config_exit(zcb->zcb_spa, SCL_CONFIG, FTAG);
3386
3387         if (BP_IS_EMBEDDED(bp)) {
3388                 zcb->zcb_embedded_blocks[BPE_GET_ETYPE(bp)]++;
3389                 zcb->zcb_embedded_histogram[BPE_GET_ETYPE(bp)]
3390                     [BPE_GET_PSIZE(bp)]++;
3391                 return;
3392         }
3393
3394         if (dump_opt['L'])
3395                 return;
3396
3397         if (BP_GET_DEDUP(bp)) {
3398                 ddt_t *ddt;
3399                 ddt_entry_t *dde;
3400
3401                 ddt = ddt_select(zcb->zcb_spa, bp);
3402                 ddt_enter(ddt);
3403                 dde = ddt_lookup(ddt, bp, B_FALSE);
3404
3405                 if (dde == NULL) {
3406                         refcnt = 0;
3407                 } else {
3408                         ddt_phys_t *ddp = ddt_phys_select(dde, bp);
3409                         ddt_phys_decref(ddp);
3410                         refcnt = ddp->ddp_refcnt;
3411                         if (ddt_phys_total_refcnt(dde) == 0)
3412                                 ddt_remove(ddt, dde);
3413                 }
3414                 ddt_exit(ddt);
3415         }
3416
3417         VERIFY3U(zio_wait(zio_claim(NULL, zcb->zcb_spa,
3418             refcnt ? 0 : spa_min_claim_txg(zcb->zcb_spa),
3419             bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
3420 }
3421
3422 static void
3423 zdb_blkptr_done(zio_t *zio)
3424 {
3425         spa_t *spa = zio->io_spa;
3426         blkptr_t *bp = zio->io_bp;
3427         int ioerr = zio->io_error;
3428         zdb_cb_t *zcb = zio->io_private;
3429         zbookmark_phys_t *zb = &zio->io_bookmark;
3430
3431         abd_free(zio->io_abd);
3432
3433         mutex_enter(&spa->spa_scrub_lock);
3434         spa->spa_load_verify_ios--;
3435         cv_broadcast(&spa->spa_scrub_io_cv);
3436
3437         if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
3438                 char blkbuf[BP_SPRINTF_LEN];
3439
3440                 zcb->zcb_haderrors = 1;
3441                 zcb->zcb_errors[ioerr]++;
3442
3443                 if (dump_opt['b'] >= 2)
3444                         snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
3445                 else
3446                         blkbuf[0] = '\0';
3447
3448                 (void) printf("zdb_blkptr_cb: "
3449                     "Got error %d reading "
3450                     "<%llu, %llu, %lld, %llx> %s -- skipping\n",
3451                     ioerr,
3452                     (u_longlong_t)zb->zb_objset,
3453                     (u_longlong_t)zb->zb_object,
3454                     (u_longlong_t)zb->zb_level,
3455                     (u_longlong_t)zb->zb_blkid,
3456                     blkbuf);
3457         }
3458         mutex_exit(&spa->spa_scrub_lock);
3459 }
3460
3461 static int
3462 zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
3463     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
3464 {
3465         zdb_cb_t *zcb = arg;
3466         dmu_object_type_t type;
3467         boolean_t is_metadata;
3468
3469         if (bp == NULL)
3470                 return (0);
3471
3472         if (dump_opt['b'] >= 5 && bp->blk_birth > 0) {
3473                 char blkbuf[BP_SPRINTF_LEN];
3474                 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
3475                 (void) printf("objset %llu object %llu "
3476                     "level %lld offset 0x%llx %s\n",
3477                     (u_longlong_t)zb->zb_objset,
3478                     (u_longlong_t)zb->zb_object,
3479                     (longlong_t)zb->zb_level,
3480                     (u_longlong_t)blkid2offset(dnp, bp, zb),
3481                     blkbuf);
3482         }
3483
3484         if (BP_IS_HOLE(bp))
3485                 return (0);
3486
3487         type = BP_GET_TYPE(bp);
3488
3489         zdb_count_block(zcb, zilog, bp,
3490             (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
3491
3492         is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
3493
3494         if (!BP_IS_EMBEDDED(bp) &&
3495             (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata))) {
3496                 size_t size = BP_GET_PSIZE(bp);
3497                 abd_t *abd = abd_alloc(size, B_FALSE);
3498                 int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
3499
3500                 /* If it's an intent log block, failure is expected. */
3501                 if (zb->zb_level == ZB_ZIL_LEVEL)
3502                         flags |= ZIO_FLAG_SPECULATIVE;
3503
3504                 mutex_enter(&spa->spa_scrub_lock);
3505                 while (spa->spa_load_verify_ios > max_inflight)
3506                         cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
3507                 spa->spa_load_verify_ios++;
3508                 mutex_exit(&spa->spa_scrub_lock);
3509
3510                 zio_nowait(zio_read(NULL, spa, bp, abd, size,
3511                     zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
3512         }
3513
3514         zcb->zcb_readfails = 0;
3515
3516         /* only call gethrtime() every 100 blocks */
3517         static int iters;
3518         if (++iters > 100)
3519                 iters = 0;
3520         else
3521                 return (0);
3522
3523         if (dump_opt['b'] < 5 && gethrtime() > zcb->zcb_lastprint + NANOSEC) {
3524                 uint64_t now = gethrtime();
3525                 char buf[10];
3526                 uint64_t bytes = zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL].zb_asize;
3527                 int kb_per_sec =
3528                     1 + bytes / (1 + ((now - zcb->zcb_start) / 1000 / 1000));
3529                 int sec_remaining =
3530                     (zcb->zcb_totalasize - bytes) / 1024 / kb_per_sec;
3531
3532                 /* make sure nicenum has enough space */
3533                 CTASSERT(sizeof (buf) >= NN_NUMBUF_SZ);
3534
3535                 zfs_nicebytes(bytes, buf, sizeof (buf));
3536                 (void) fprintf(stderr,
3537                     "\r%5s completed (%4dMB/s) "
3538                     "estimated time remaining: %uhr %02umin %02usec        ",
3539                     buf, kb_per_sec / 1024,
3540                     sec_remaining / 60 / 60,
3541                     sec_remaining / 60 % 60,
3542                     sec_remaining % 60);
3543
3544                 zcb->zcb_lastprint = now;
3545         }
3546
3547         return (0);
3548 }
3549
3550 static void
3551 zdb_leak(void *arg, uint64_t start, uint64_t size)
3552 {
3553         vdev_t *vd = arg;
3554
3555         (void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
3556             (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
3557 }
3558
3559 static metaslab_ops_t zdb_metaslab_ops = {
3560         NULL    /* alloc */
3561 };
3562
3563 /* ARGSUSED */
3564 static void
3565 claim_segment_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
3566     uint64_t size, void *arg)
3567 {
3568         /*
3569          * This callback was called through a remap from
3570          * a device being removed. Therefore, the vdev that
3571          * this callback is applied to is a concrete
3572          * vdev.
3573          */
3574         ASSERT(vdev_is_concrete(vd));
3575
3576         VERIFY0(metaslab_claim_impl(vd, offset, size,
3577             spa_min_claim_txg(vd->vdev_spa)));
3578 }
3579
3580 static void
3581 claim_segment_cb(void *arg, uint64_t offset, uint64_t size)
3582 {
3583         vdev_t *vd = arg;
3584
3585         vdev_indirect_ops.vdev_op_remap(vd, offset, size,
3586             claim_segment_impl_cb, NULL);
3587 }
3588
3589 /*
3590  * After accounting for all allocated blocks that are directly referenced,
3591  * we might have missed a reference to a block from a partially complete
3592  * (and thus unused) indirect mapping object. We perform a secondary pass
3593  * through the metaslabs we have already mapped and claim the destination
3594  * blocks.
3595  */
3596 static void
3597 zdb_claim_removing(spa_t *spa, zdb_cb_t *zcb)
3598 {
3599         if (spa->spa_vdev_removal == NULL)
3600                 return;
3601
3602         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3603
3604         spa_vdev_removal_t *svr = spa->spa_vdev_removal;
3605         vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
3606         vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3607
3608         for (uint64_t msi = 0; msi < vd->vdev_ms_count; msi++) {
3609                 metaslab_t *msp = vd->vdev_ms[msi];
3610
3611                 if (msp->ms_start >= vdev_indirect_mapping_max_offset(vim))
3612                         break;
3613
3614                 ASSERT0(range_tree_space(svr->svr_allocd_segs));
3615
3616                 if (msp->ms_sm != NULL) {
3617                         VERIFY0(space_map_load(msp->ms_sm,
3618                             svr->svr_allocd_segs, SM_ALLOC));
3619
3620                         /*
3621                          * Clear everything past what has been synced unless
3622                          * it's past the spacemap, because we have not allocated
3623                          * mappings for it yet.
3624                          */
3625                         uint64_t vim_max_offset =
3626                             vdev_indirect_mapping_max_offset(vim);
3627                         uint64_t sm_end = msp->ms_sm->sm_start +
3628                             msp->ms_sm->sm_size;
3629                         if (sm_end > vim_max_offset)
3630                                 range_tree_clear(svr->svr_allocd_segs,
3631                                     vim_max_offset, sm_end - vim_max_offset);
3632                 }
3633
3634                 zcb->zcb_removing_size +=
3635                     range_tree_space(svr->svr_allocd_segs);
3636                 range_tree_vacate(svr->svr_allocd_segs, claim_segment_cb, vd);
3637         }
3638
3639         spa_config_exit(spa, SCL_CONFIG, FTAG);
3640 }
3641
3642 /* ARGSUSED */
3643 static int
3644 increment_indirect_mapping_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
3645 {
3646         zdb_cb_t *zcb = arg;
3647         spa_t *spa = zcb->zcb_spa;
3648         vdev_t *vd;
3649         const dva_t *dva = &bp->blk_dva[0];
3650
3651         ASSERT(!dump_opt['L']);
3652         ASSERT3U(BP_GET_NDVAS(bp), ==, 1);
3653
3654         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3655         vd = vdev_lookup_top(zcb->zcb_spa, DVA_GET_VDEV(dva));
3656         ASSERT3P(vd, !=, NULL);
3657         spa_config_exit(spa, SCL_VDEV, FTAG);
3658
3659         ASSERT(vd->vdev_indirect_config.vic_mapping_object != 0);
3660         ASSERT3P(zcb->zcb_vd_obsolete_counts[vd->vdev_id], !=, NULL);
3661
3662         vdev_indirect_mapping_increment_obsolete_count(
3663             vd->vdev_indirect_mapping,
3664             DVA_GET_OFFSET(dva), DVA_GET_ASIZE(dva),
3665             zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
3666
3667         return (0);
3668 }
3669
3670 static uint32_t *
3671 zdb_load_obsolete_counts(vdev_t *vd)
3672 {
3673         vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3674         spa_t *spa = vd->vdev_spa;
3675         spa_condensing_indirect_phys_t *scip =
3676             &spa->spa_condensing_indirect_phys;
3677         uint64_t obsolete_sm_object;
3678         uint32_t *counts;
3679
3680         VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
3681         EQUIV(obsolete_sm_object != 0, vd->vdev_obsolete_sm != NULL);
3682         counts = vdev_indirect_mapping_load_obsolete_counts(vim);
3683         if (vd->vdev_obsolete_sm != NULL) {
3684                 vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
3685                     vd->vdev_obsolete_sm);
3686         }
3687         if (scip->scip_vdev == vd->vdev_id &&
3688             scip->scip_prev_obsolete_sm_object != 0) {
3689                 space_map_t *prev_obsolete_sm = NULL;
3690                 VERIFY0(space_map_open(&prev_obsolete_sm, spa->spa_meta_objset,
3691                     scip->scip_prev_obsolete_sm_object, 0, vd->vdev_asize, 0));
3692                 space_map_update(prev_obsolete_sm);
3693                 vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
3694                     prev_obsolete_sm);
3695                 space_map_close(prev_obsolete_sm);
3696         }
3697         return (counts);
3698 }
3699
3700 static void
3701 zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
3702 {
3703         ddt_bookmark_t ddb;
3704         ddt_entry_t dde;
3705         int error;
3706         int p;
3707
3708         bzero(&ddb, sizeof (ddb));
3709         while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
3710                 blkptr_t blk;
3711                 ddt_phys_t *ddp = dde.dde_phys;
3712
3713                 if (ddb.ddb_class == DDT_CLASS_UNIQUE)
3714                         return;
3715
3716                 ASSERT(ddt_phys_total_refcnt(&dde) > 1);
3717
3718                 for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
3719                         if (ddp->ddp_phys_birth == 0)
3720                                 continue;
3721                         ddt_bp_create(ddb.ddb_checksum,
3722                             &dde.dde_key, ddp, &blk);
3723                         if (p == DDT_PHYS_DITTO) {
3724                                 zdb_count_block(zcb, NULL, &blk, ZDB_OT_DITTO);
3725                         } else {
3726                                 zcb->zcb_dedup_asize +=
3727                                     BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
3728                                 zcb->zcb_dedup_blocks++;
3729                         }
3730                 }
3731                 if (!dump_opt['L']) {
3732                         ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
3733                         ddt_enter(ddt);
3734                         VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
3735                         ddt_exit(ddt);
3736                 }
3737         }
3738
3739         ASSERT(error == ENOENT);
3740 }
3741
3742 typedef struct checkpoint_sm_exclude_entry_arg {
3743         vdev_t *cseea_vd;
3744         uint64_t cseea_checkpoint_size;
3745 } checkpoint_sm_exclude_entry_arg_t;
3746
3747 static int
3748 checkpoint_sm_exclude_entry_cb(space_map_entry_t *sme, void *arg)
3749 {
3750         checkpoint_sm_exclude_entry_arg_t *cseea = arg;
3751         vdev_t *vd = cseea->cseea_vd;
3752         metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
3753         uint64_t end = sme->sme_offset + sme->sme_run;
3754
3755         ASSERT(sme->sme_type == SM_FREE);
3756
3757         /*
3758          * Since the vdev_checkpoint_sm exists in the vdev level
3759          * and the ms_sm space maps exist in the metaslab level,
3760          * an entry in the checkpoint space map could theoretically
3761          * cross the boundaries of the metaslab that it belongs.
3762          *
3763          * In reality, because of the way that we populate and
3764          * manipulate the checkpoint's space maps currently,
3765          * there shouldn't be any entries that cross metaslabs.
3766          * Hence the assertion below.
3767          *
3768          * That said, there is no fundamental requirement that
3769          * the checkpoint's space map entries should not cross
3770          * metaslab boundaries. So if needed we could add code
3771          * that handles metaslab-crossing segments in the future.
3772          */
3773         VERIFY3U(sme->sme_offset, >=, ms->ms_start);
3774         VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
3775
3776         /*
3777          * By removing the entry from the allocated segments we
3778          * also verify that the entry is there to begin with.
3779          */
3780         mutex_enter(&ms->ms_lock);
3781         range_tree_remove(ms->ms_allocatable, sme->sme_offset, sme->sme_run);
3782         mutex_exit(&ms->ms_lock);
3783
3784         cseea->cseea_checkpoint_size += sme->sme_run;
3785         return (0);
3786 }
3787
3788 static void
3789 zdb_leak_init_vdev_exclude_checkpoint(vdev_t *vd, zdb_cb_t *zcb)
3790 {
3791         spa_t *spa = vd->vdev_spa;
3792         space_map_t *checkpoint_sm = NULL;
3793         uint64_t checkpoint_sm_obj;
3794
3795         /*
3796          * If there is no vdev_top_zap, we are in a pool whose
3797          * version predates the pool checkpoint feature.
3798          */
3799         if (vd->vdev_top_zap == 0)
3800                 return;
3801
3802         /*
3803          * If there is no reference of the vdev_checkpoint_sm in
3804          * the vdev_top_zap, then one of the following scenarios
3805          * is true:
3806          *
3807          * 1] There is no checkpoint
3808          * 2] There is a checkpoint, but no checkpointed blocks
3809          *    have been freed yet
3810          * 3] The current vdev is indirect
3811          *
3812          * In these cases we return immediately.
3813          */
3814         if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
3815             VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
3816                 return;
3817
3818         VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
3819             VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1,
3820             &checkpoint_sm_obj));
3821
3822         checkpoint_sm_exclude_entry_arg_t cseea;
3823         cseea.cseea_vd = vd;
3824         cseea.cseea_checkpoint_size = 0;
3825
3826         VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
3827             checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
3828         space_map_update(checkpoint_sm);
3829
3830         VERIFY0(space_map_iterate(checkpoint_sm,
3831             checkpoint_sm_exclude_entry_cb, &cseea));
3832         space_map_close(checkpoint_sm);
3833
3834         zcb->zcb_checkpoint_size += cseea.cseea_checkpoint_size;
3835 }
3836
3837 static void
3838 zdb_leak_init_exclude_checkpoint(spa_t *spa, zdb_cb_t *zcb)
3839 {
3840         vdev_t *rvd = spa->spa_root_vdev;
3841         for (uint64_t c = 0; c < rvd->vdev_children; c++) {
3842                 ASSERT3U(c, ==, rvd->vdev_child[c]->vdev_id);
3843                 zdb_leak_init_vdev_exclude_checkpoint(rvd->vdev_child[c], zcb);
3844         }
3845 }
3846
3847 static void
3848 load_concrete_ms_allocatable_trees(spa_t *spa, maptype_t maptype)
3849 {
3850         vdev_t *rvd = spa->spa_root_vdev;
3851         for (uint64_t i = 0; i < rvd->vdev_children; i++) {
3852                 vdev_t *vd = rvd->vdev_child[i];
3853
3854                 ASSERT3U(i, ==, vd->vdev_id);
3855
3856                 if (vd->vdev_ops == &vdev_indirect_ops)
3857                         continue;
3858
3859                 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
3860                         metaslab_t *msp = vd->vdev_ms[m];
3861
3862                         (void) fprintf(stderr,
3863                             "\rloading concrete vdev %llu, "
3864                             "metaslab %llu of %llu ...",
3865                             (longlong_t)vd->vdev_id,
3866                             (longlong_t)msp->ms_id,
3867                             (longlong_t)vd->vdev_ms_count);
3868
3869                         mutex_enter(&msp->ms_lock);
3870                         metaslab_unload(msp);
3871
3872                         /*
3873                          * We don't want to spend the CPU manipulating the
3874                          * size-ordered tree, so clear the range_tree ops.
3875                          */
3876                         msp->ms_allocatable->rt_ops = NULL;
3877
3878                         if (msp->ms_sm != NULL) {
3879                                 VERIFY0(space_map_load(msp->ms_sm,
3880                                     msp->ms_allocatable, maptype));
3881                         }
3882                         if (!msp->ms_loaded)
3883                                 msp->ms_loaded = B_TRUE;
3884                         mutex_exit(&msp->ms_lock);
3885                 }
3886         }
3887 }
3888
3889 /*
3890  * vm_idxp is an in-out parameter which (for indirect vdevs) is the
3891  * index in vim_entries that has the first entry in this metaslab.
3892  * On return, it will be set to the first entry after this metaslab.
3893  */
3894 static void
3895 load_indirect_ms_allocatable_tree(vdev_t *vd, metaslab_t *msp,
3896     uint64_t *vim_idxp)
3897 {
3898         vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3899
3900         mutex_enter(&msp->ms_lock);
3901         metaslab_unload(msp);
3902
3903         /*
3904          * We don't want to spend the CPU manipulating the
3905          * size-ordered tree, so clear the range_tree ops.
3906          */
3907         msp->ms_allocatable->rt_ops = NULL;
3908
3909         for (; *vim_idxp < vdev_indirect_mapping_num_entries(vim);
3910             (*vim_idxp)++) {
3911                 vdev_indirect_mapping_entry_phys_t *vimep =
3912                     &vim->vim_entries[*vim_idxp];
3913                 uint64_t ent_offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
3914                 uint64_t ent_len = DVA_GET_ASIZE(&vimep->vimep_dst);
3915                 ASSERT3U(ent_offset, >=, msp->ms_start);
3916                 if (ent_offset >= msp->ms_start + msp->ms_size)
3917                         break;
3918
3919                 /*
3920                  * Mappings do not cross metaslab boundaries,
3921                  * because we create them by walking the metaslabs.
3922                  */
3923                 ASSERT3U(ent_offset + ent_len, <=,
3924                     msp->ms_start + msp->ms_size);
3925                 range_tree_add(msp->ms_allocatable, ent_offset, ent_len);
3926         }
3927
3928         if (!msp->ms_loaded)
3929                 msp->ms_loaded = B_TRUE;
3930         mutex_exit(&msp->ms_lock);
3931 }
3932
3933 static void
3934 zdb_leak_init_prepare_indirect_vdevs(spa_t *spa, zdb_cb_t *zcb)
3935 {
3936         vdev_t *rvd = spa->spa_root_vdev;
3937         for (uint64_t c = 0; c < rvd->vdev_children; c++) {
3938                 vdev_t *vd = rvd->vdev_child[c];
3939
3940                 ASSERT3U(c, ==, vd->vdev_id);
3941
3942                 if (vd->vdev_ops != &vdev_indirect_ops)
3943                         continue;
3944
3945                 /*
3946                  * Note: we don't check for mapping leaks on
3947                  * removing vdevs because their ms_allocatable's
3948                  * are used to look for leaks in allocated space.
3949                  */
3950                 zcb->zcb_vd_obsolete_counts[c] = zdb_load_obsolete_counts(vd);
3951
3952                 /*
3953                  * Normally, indirect vdevs don't have any
3954                  * metaslabs.  We want to set them up for
3955                  * zio_claim().
3956                  */
3957                 VERIFY0(vdev_metaslab_init(vd, 0));
3958
3959                 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3960                 uint64_t vim_idx = 0;
3961                 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
3962
3963                         (void) fprintf(stderr,
3964                             "\rloading indirect vdev %llu, "
3965                             "metaslab %llu of %llu ...",
3966                             (longlong_t)vd->vdev_id,
3967                             (longlong_t)vd->vdev_ms[m]->ms_id,
3968                             (longlong_t)vd->vdev_ms_count);
3969
3970                         load_indirect_ms_allocatable_tree(vd, vd->vdev_ms[m],
3971                             &vim_idx);
3972                 }
3973                 ASSERT3U(vim_idx, ==, vdev_indirect_mapping_num_entries(vim));
3974         }
3975 }
3976
3977 static void
3978 zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
3979 {
3980         zcb->zcb_spa = spa;
3981
3982         if (!dump_opt['L']) {
3983                 dsl_pool_t *dp = spa->spa_dsl_pool;
3984                 vdev_t *rvd = spa->spa_root_vdev;
3985
3986                 /*
3987                  * We are going to be changing the meaning of the metaslab's
3988                  * ms_allocatable.  Ensure that the allocator doesn't try to
3989                  * use the tree.
3990                  */
3991                 spa->spa_normal_class->mc_ops = &zdb_metaslab_ops;
3992                 spa->spa_log_class->mc_ops = &zdb_metaslab_ops;
3993
3994                 zcb->zcb_vd_obsolete_counts =
3995                     umem_zalloc(rvd->vdev_children * sizeof (uint32_t *),
3996                     UMEM_NOFAIL);
3997
3998                 /*
3999                  * For leak detection, we overload the ms_allocatable trees
4000                  * to contain allocated segments instead of free segments.
4001                  * As a result, we can't use the normal metaslab_load/unload
4002                  * interfaces.
4003                  */
4004                 zdb_leak_init_prepare_indirect_vdevs(spa, zcb);
4005                 load_concrete_ms_allocatable_trees(spa, SM_ALLOC);
4006
4007                 /*
4008                  * On load_concrete_ms_allocatable_trees() we loaded all the
4009                  * allocated entries from the ms_sm to the ms_allocatable for
4010                  * each metaslab. If the pool has a checkpoint or is in the
4011                  * middle of discarding a checkpoint, some of these blocks
4012                  * may have been freed but their ms_sm may not have been
4013                  * updated because they are referenced by the checkpoint. In
4014                  * order to avoid false-positives during leak-detection, we
4015                  * go through the vdev's checkpoint space map and exclude all
4016                  * its entries from their relevant ms_allocatable.
4017                  *
4018                  * We also aggregate the space held by the checkpoint and add
4019                  * it to zcb_checkpoint_size.
4020                  *
4021                  * Note that at this point we are also verifying that all the
4022                  * entries on the checkpoint_sm are marked as allocated in
4023                  * the ms_sm of their relevant metaslab.
4024                  * [see comment in checkpoint_sm_exclude_entry_cb()]
4025                  */
4026                 zdb_leak_init_exclude_checkpoint(spa, zcb);
4027
4028                 /* for cleaner progress output */
4029                 (void) fprintf(stderr, "\n");
4030
4031                 if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
4032                         ASSERT(spa_feature_is_enabled(spa,
4033                             SPA_FEATURE_DEVICE_REMOVAL));
4034                         (void) bpobj_iterate_nofree(&dp->dp_obsolete_bpobj,
4035                             increment_indirect_mapping_cb, zcb, NULL);
4036                 }
4037         } else {
4038                 /*
4039                  * If leak tracing is disabled, we still need to consider
4040                  * any checkpointed space in our space verification.
4041                  */
4042                 zcb->zcb_checkpoint_size += spa_get_checkpoint_space(spa);
4043         }
4044
4045         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4046         zdb_ddt_leak_init(spa, zcb);
4047         spa_config_exit(spa, SCL_CONFIG, FTAG);
4048 }
4049
4050 static boolean_t
4051 zdb_check_for_obsolete_leaks(vdev_t *vd, zdb_cb_t *zcb)
4052 {
4053         boolean_t leaks = B_FALSE;
4054         vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
4055         uint64_t total_leaked = 0;
4056         boolean_t are_precise = B_FALSE;
4057
4058         ASSERT(vim != NULL);
4059
4060         for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
4061                 vdev_indirect_mapping_entry_phys_t *vimep =
4062                     &vim->vim_entries[i];
4063                 uint64_t obsolete_bytes = 0;
4064                 uint64_t offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
4065                 metaslab_t *msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
4066
4067                 /*
4068                  * This is not very efficient but it's easy to
4069                  * verify correctness.
4070                  */
4071                 for (uint64_t inner_offset = 0;
4072                     inner_offset < DVA_GET_ASIZE(&vimep->vimep_dst);
4073                     inner_offset += 1 << vd->vdev_ashift) {
4074                         if (range_tree_contains(msp->ms_allocatable,
4075                             offset + inner_offset, 1 << vd->vdev_ashift)) {
4076                                 obsolete_bytes += 1 << vd->vdev_ashift;
4077                         }
4078                 }
4079
4080                 int64_t bytes_leaked = obsolete_bytes -
4081                     zcb->zcb_vd_obsolete_counts[vd->vdev_id][i];
4082                 ASSERT3U(DVA_GET_ASIZE(&vimep->vimep_dst), >=,
4083                     zcb->zcb_vd_obsolete_counts[vd->vdev_id][i]);
4084
4085                 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
4086                 if (bytes_leaked != 0 && (are_precise || dump_opt['d'] >= 5)) {
4087                         (void) printf("obsolete indirect mapping count "
4088                             "mismatch on %llu:%llx:%llx : %llx bytes leaked\n",
4089                             (u_longlong_t)vd->vdev_id,
4090                             (u_longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
4091                             (u_longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
4092                             (u_longlong_t)bytes_leaked);
4093                 }
4094                 total_leaked += ABS(bytes_leaked);
4095         }
4096
4097         VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
4098         if (!are_precise && total_leaked > 0) {
4099                 int pct_leaked = total_leaked * 100 /
4100                     vdev_indirect_mapping_bytes_mapped(vim);
4101                 (void) printf("cannot verify obsolete indirect mapping "
4102                     "counts of vdev %llu because precise feature was not "
4103                     "enabled when it was removed: %d%% (%llx bytes) of mapping"
4104                     "unreferenced\n",
4105                     (u_longlong_t)vd->vdev_id, pct_leaked,
4106                     (u_longlong_t)total_leaked);
4107         } else if (total_leaked > 0) {
4108                 (void) printf("obsolete indirect mapping count mismatch "
4109                     "for vdev %llu -- %llx total bytes mismatched\n",
4110                     (u_longlong_t)vd->vdev_id,
4111                     (u_longlong_t)total_leaked);
4112                 leaks |= B_TRUE;
4113         }
4114
4115         vdev_indirect_mapping_free_obsolete_counts(vim,
4116             zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
4117         zcb->zcb_vd_obsolete_counts[vd->vdev_id] = NULL;
4118
4119         return (leaks);
4120 }
4121
4122 static boolean_t
4123 zdb_leak_fini(spa_t *spa, zdb_cb_t *zcb)
4124 {
4125         boolean_t leaks = B_FALSE;
4126         if (!dump_opt['L']) {
4127                 vdev_t *rvd = spa->spa_root_vdev;
4128                 for (unsigned c = 0; c < rvd->vdev_children; c++) {
4129                         vdev_t *vd = rvd->vdev_child[c];
4130                         ASSERTV(metaslab_group_t *mg = vd->vdev_mg);
4131
4132                         if (zcb->zcb_vd_obsolete_counts[c] != NULL) {
4133                                 leaks |= zdb_check_for_obsolete_leaks(vd, zcb);
4134                         }
4135
4136                         for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
4137                                 metaslab_t *msp = vd->vdev_ms[m];
4138                                 ASSERT3P(mg, ==, msp->ms_group);
4139
4140                                 /*
4141                                  * ms_allocatable has been overloaded
4142                                  * to contain allocated segments. Now that
4143                                  * we finished traversing all blocks, any
4144                                  * block that remains in the ms_allocatable
4145                                  * represents an allocated block that we
4146                                  * did not claim during the traversal.
4147                                  * Claimed blocks would have been removed
4148                                  * from the ms_allocatable.  For indirect
4149                                  * vdevs, space remaining in the tree
4150                                  * represents parts of the mapping that are
4151                                  * not referenced, which is not a bug.
4152                                  */
4153                                 if (vd->vdev_ops == &vdev_indirect_ops) {
4154                                         range_tree_vacate(msp->ms_allocatable,
4155                                             NULL, NULL);
4156                                 } else {
4157                                         range_tree_vacate(msp->ms_allocatable,
4158                                             zdb_leak, vd);
4159                                 }
4160
4161                                 if (msp->ms_loaded)
4162                                         msp->ms_loaded = B_FALSE;
4163                         }
4164                 }
4165
4166                 umem_free(zcb->zcb_vd_obsolete_counts,
4167                     rvd->vdev_children * sizeof (uint32_t *));
4168                 zcb->zcb_vd_obsolete_counts = NULL;
4169         }
4170         return (leaks);
4171 }
4172
4173 /* ARGSUSED */
4174 static int
4175 count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
4176 {
4177         zdb_cb_t *zcb = arg;
4178
4179         if (dump_opt['b'] >= 5) {
4180                 char blkbuf[BP_SPRINTF_LEN];
4181                 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
4182                 (void) printf("[%s] %s\n",
4183                     "deferred free", blkbuf);
4184         }
4185         zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
4186         return (0);
4187 }
4188
4189 static int
4190 dump_block_stats(spa_t *spa)
4191 {
4192         zdb_cb_t zcb;
4193         zdb_blkstats_t *zb, *tzb;
4194         uint64_t norm_alloc, norm_space, total_alloc, total_found;
4195         int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
4196             TRAVERSE_NO_DECRYPT | TRAVERSE_HARD;
4197         boolean_t leaks = B_FALSE;
4198         int e, c, err;
4199         bp_embedded_type_t i;
4200
4201         bzero(&zcb, sizeof (zcb));
4202         (void) printf("\nTraversing all blocks %s%s%s%s%s...\n\n",
4203             (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
4204             (dump_opt['c'] == 1) ? "metadata " : "",
4205             dump_opt['c'] ? "checksums " : "",
4206             (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
4207             !dump_opt['L'] ? "nothing leaked " : "");
4208
4209         /*
4210          * Load all space maps as SM_ALLOC maps, then traverse the pool
4211          * claiming each block we discover.  If the pool is perfectly
4212          * consistent, the space maps will be empty when we're done.
4213          * Anything left over is a leak; any block we can't claim (because
4214          * it's not part of any space map) is a double allocation,
4215          * reference to a freed block, or an unclaimed log block.
4216          */
4217         bzero(&zcb, sizeof (zdb_cb_t));
4218         zdb_leak_init(spa, &zcb);
4219
4220         /*
4221          * If there's a deferred-free bplist, process that first.
4222          */
4223         (void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
4224             count_block_cb, &zcb, NULL);
4225
4226         if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
4227                 (void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
4228                     count_block_cb, &zcb, NULL);
4229         }
4230
4231         zdb_claim_removing(spa, &zcb);
4232
4233         if (spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
4234                 VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
4235                     spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
4236                     &zcb, NULL));
4237         }
4238
4239         if (dump_opt['c'] > 1)
4240                 flags |= TRAVERSE_PREFETCH_DATA;
4241
4242         zcb.zcb_totalasize = metaslab_class_get_alloc(spa_normal_class(spa));
4243         zcb.zcb_totalasize += metaslab_class_get_alloc(spa_special_class(spa));
4244         zcb.zcb_totalasize += metaslab_class_get_alloc(spa_dedup_class(spa));
4245         zcb.zcb_start = zcb.zcb_lastprint = gethrtime();
4246         err = traverse_pool(spa, 0, flags, zdb_blkptr_cb, &zcb);
4247
4248         /*
4249          * If we've traversed the data blocks then we need to wait for those
4250          * I/Os to complete. We leverage "The Godfather" zio to wait on
4251          * all async I/Os to complete.
4252          */
4253         if (dump_opt['c']) {
4254                 for (c = 0; c < max_ncpus; c++) {
4255                         (void) zio_wait(spa->spa_async_zio_root[c]);
4256                         spa->spa_async_zio_root[c] = zio_root(spa, NULL, NULL,
4257                             ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
4258                             ZIO_FLAG_GODFATHER);
4259                 }
4260         }
4261
4262         /*
4263          * Done after zio_wait() since zcb_haderrors is modified in
4264          * zdb_blkptr_done()
4265          */
4266         zcb.zcb_haderrors |= err;
4267
4268         if (zcb.zcb_haderrors) {
4269                 (void) printf("\nError counts:\n\n");
4270                 (void) printf("\t%5s  %s\n", "errno", "count");
4271                 for (e = 0; e < 256; e++) {
4272                         if (zcb.zcb_errors[e] != 0) {
4273                                 (void) printf("\t%5d  %llu\n",
4274                                     e, (u_longlong_t)zcb.zcb_errors[e]);
4275                         }
4276                 }
4277         }
4278
4279         /*
4280          * Report any leaked segments.
4281          */
4282         leaks |= zdb_leak_fini(spa, &zcb);
4283
4284         tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
4285
4286         norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
4287         norm_space = metaslab_class_get_space(spa_normal_class(spa));
4288
4289         total_alloc = norm_alloc +
4290             metaslab_class_get_alloc(spa_log_class(spa)) +
4291             metaslab_class_get_alloc(spa_special_class(spa)) +
4292             metaslab_class_get_alloc(spa_dedup_class(spa));
4293         total_found = tzb->zb_asize - zcb.zcb_dedup_asize +
4294             zcb.zcb_removing_size + zcb.zcb_checkpoint_size;
4295
4296         if (total_found == total_alloc) {
4297                 if (!dump_opt['L'])
4298                         (void) printf("\n\tNo leaks (block sum matches space"
4299                             " maps exactly)\n");
4300         } else {
4301                 (void) printf("block traversal size %llu != alloc %llu "
4302                     "(%s %lld)\n",
4303                     (u_longlong_t)total_found,
4304                     (u_longlong_t)total_alloc,
4305                     (dump_opt['L']) ? "unreachable" : "leaked",
4306                     (longlong_t)(total_alloc - total_found));
4307                 leaks = B_TRUE;
4308         }
4309
4310         if (tzb->zb_count == 0)
4311                 return (2);
4312
4313         (void) printf("\n");
4314         (void) printf("\t%-16s %14llu\n", "bp count:",
4315             (u_longlong_t)tzb->zb_count);
4316         (void) printf("\t%-16s %14llu\n", "ganged count:",
4317             (longlong_t)tzb->zb_gangs);
4318         (void) printf("\t%-16s %14llu      avg: %6llu\n", "bp logical:",
4319             (u_longlong_t)tzb->zb_lsize,
4320             (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
4321         (void) printf("\t%-16s %14llu      avg: %6llu     compression: %6.2f\n",
4322             "bp physical:", (u_longlong_t)tzb->zb_psize,
4323             (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
4324             (double)tzb->zb_lsize / tzb->zb_psize);
4325         (void) printf("\t%-16s %14llu      avg: %6llu     compression: %6.2f\n",
4326             "bp allocated:", (u_longlong_t)tzb->zb_asize,
4327             (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
4328             (double)tzb->zb_lsize / tzb->zb_asize);
4329         (void) printf("\t%-16s %14llu    ref>1: %6llu   deduplication: %6.2f\n",
4330             "bp deduped:", (u_longlong_t)zcb.zcb_dedup_asize,
4331             (u_longlong_t)zcb.zcb_dedup_blocks,
4332             (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
4333         (void) printf("\t%-16s %14llu     used: %5.2f%%\n", "Normal class:",
4334             (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
4335
4336         if (spa_special_class(spa)->mc_rotor != NULL) {
4337                 uint64_t alloc = metaslab_class_get_alloc(
4338                     spa_special_class(spa));
4339                 uint64_t space = metaslab_class_get_space(
4340                     spa_special_class(spa));
4341
4342                 (void) printf("\t%-16s %14llu     used: %5.2f%%\n",
4343                     "Special class", (u_longlong_t)alloc,
4344                     100.0 * alloc / space);
4345         }
4346
4347         if (spa_dedup_class(spa)->mc_rotor != NULL) {
4348                 uint64_t alloc = metaslab_class_get_alloc(
4349                     spa_dedup_class(spa));
4350                 uint64_t space = metaslab_class_get_space(
4351                     spa_dedup_class(spa));
4352
4353                 (void) printf("\t%-16s %14llu     used: %5.2f%%\n",
4354                     "Dedup class", (u_longlong_t)alloc,
4355                     100.0 * alloc / space);
4356         }
4357
4358         for (i = 0; i < NUM_BP_EMBEDDED_TYPES; i++) {
4359                 if (zcb.zcb_embedded_blocks[i] == 0)
4360                         continue;
4361                 (void) printf("\n");
4362                 (void) printf("\tadditional, non-pointer bps of type %u: "
4363                     "%10llu\n",
4364                     i, (u_longlong_t)zcb.zcb_embedded_blocks[i]);
4365
4366                 if (dump_opt['b'] >= 3) {
4367                         (void) printf("\t number of (compressed) bytes:  "
4368                             "number of bps\n");
4369                         dump_histogram(zcb.zcb_embedded_histogram[i],
4370                             sizeof (zcb.zcb_embedded_histogram[i]) /
4371                             sizeof (zcb.zcb_embedded_histogram[i][0]), 0);
4372                 }
4373         }
4374
4375         if (tzb->zb_ditto_samevdev != 0) {
4376                 (void) printf("\tDittoed blocks on same vdev: %llu\n",
4377                     (longlong_t)tzb->zb_ditto_samevdev);
4378         }
4379         if (tzb->zb_ditto_same_ms != 0) {
4380                 (void) printf("\tDittoed blocks in same metaslab: %llu\n",
4381                     (longlong_t)tzb->zb_ditto_same_ms);
4382         }
4383
4384         for (uint64_t v = 0; v < spa->spa_root_vdev->vdev_children; v++) {
4385                 vdev_t *vd = spa->spa_root_vdev->vdev_child[v];
4386                 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
4387
4388                 if (vim == NULL) {
4389                         continue;
4390                 }
4391
4392                 char mem[32];
4393                 zdb_nicenum(vdev_indirect_mapping_num_entries(vim),
4394                     mem, vdev_indirect_mapping_size(vim));
4395
4396                 (void) printf("\tindirect vdev id %llu has %llu segments "
4397                     "(%s in memory)\n",
4398                     (longlong_t)vd->vdev_id,
4399                     (longlong_t)vdev_indirect_mapping_num_entries(vim), mem);
4400         }
4401
4402         if (dump_opt['b'] >= 2) {
4403                 int l, t, level;
4404                 (void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
4405                     "\t  avg\t comp\t%%Total\tType\n");
4406
4407                 for (t = 0; t <= ZDB_OT_TOTAL; t++) {
4408                         char csize[32], lsize[32], psize[32], asize[32];
4409                         char avg[32], gang[32];
4410                         const char *typename;
4411
4412                         /* make sure nicenum has enough space */
4413                         CTASSERT(sizeof (csize) >= NN_NUMBUF_SZ);
4414                         CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
4415                         CTASSERT(sizeof (psize) >= NN_NUMBUF_SZ);
4416                         CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
4417                         CTASSERT(sizeof (avg) >= NN_NUMBUF_SZ);
4418                         CTASSERT(sizeof (gang) >= NN_NUMBUF_SZ);
4419
4420                         if (t < DMU_OT_NUMTYPES)
4421                                 typename = dmu_ot[t].ot_name;
4422                         else
4423                                 typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
4424
4425                         if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
4426                                 (void) printf("%6s\t%5s\t%5s\t%5s"
4427                                     "\t%5s\t%5s\t%6s\t%s\n",
4428                                     "-",
4429                                     "-",
4430                                     "-",
4431                                     "-",
4432                                     "-",
4433                                     "-",
4434                                     "-",
4435                                     typename);
4436                                 continue;
4437                         }
4438
4439                         for (l = ZB_TOTAL - 1; l >= -1; l--) {
4440                                 level = (l == -1 ? ZB_TOTAL : l);
4441                                 zb = &zcb.zcb_type[level][t];
4442
4443                                 if (zb->zb_asize == 0)
4444                                         continue;
4445
4446                                 if (dump_opt['b'] < 3 && level != ZB_TOTAL)
4447                                         continue;
4448
4449                                 if (level == 0 && zb->zb_asize ==
4450                                     zcb.zcb_type[ZB_TOTAL][t].zb_asize)
4451                                         continue;
4452
4453                                 zdb_nicenum(zb->zb_count, csize,
4454                                     sizeof (csize));
4455                                 zdb_nicenum(zb->zb_lsize, lsize,
4456                                     sizeof (lsize));
4457                                 zdb_nicenum(zb->zb_psize, psize,
4458                                     sizeof (psize));
4459                                 zdb_nicenum(zb->zb_asize, asize,
4460                                     sizeof (asize));
4461                                 zdb_nicenum(zb->zb_asize / zb->zb_count, avg,
4462                                     sizeof (avg));
4463                                 zdb_nicenum(zb->zb_gangs, gang, sizeof (gang));
4464
4465                                 (void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
4466                                     "\t%5.2f\t%6.2f\t",
4467                                     csize, lsize, psize, asize, avg,
4468                                     (double)zb->zb_lsize / zb->zb_psize,
4469                                     100.0 * zb->zb_asize / tzb->zb_asize);
4470
4471                                 if (level == ZB_TOTAL)
4472                                         (void) printf("%s\n", typename);
4473                                 else
4474                                         (void) printf("    L%d %s\n",
4475                                             level, typename);
4476
4477                                 if (dump_opt['b'] >= 3 && zb->zb_gangs > 0) {
4478                                         (void) printf("\t number of ganged "
4479                                             "blocks: %s\n", gang);
4480                                 }
4481
4482                                 if (dump_opt['b'] >= 4) {
4483                                         (void) printf("psize "
4484                                             "(in 512-byte sectors): "
4485                                             "number of blocks\n");
4486                                         dump_histogram(zb->zb_psize_histogram,
4487                                             PSIZE_HISTO_SIZE, 0);
4488                                 }
4489                         }
4490                 }
4491         }
4492
4493         (void) printf("\n");
4494
4495         if (leaks)
4496                 return (2);
4497
4498         if (zcb.zcb_haderrors)
4499                 return (3);
4500
4501         return (0);
4502 }
4503
4504 typedef struct zdb_ddt_entry {
4505         ddt_key_t       zdde_key;
4506         uint64_t        zdde_ref_blocks;
4507         uint64_t        zdde_ref_lsize;
4508         uint64_t        zdde_ref_psize;
4509         uint64_t        zdde_ref_dsize;
4510         avl_node_t      zdde_node;
4511 } zdb_ddt_entry_t;
4512
4513 /* ARGSUSED */
4514 static int
4515 zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
4516     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
4517 {
4518         avl_tree_t *t = arg;
4519         avl_index_t where;
4520         zdb_ddt_entry_t *zdde, zdde_search;
4521
4522         if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
4523                 return (0);
4524
4525         if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
4526                 (void) printf("traversing objset %llu, %llu objects, "
4527                     "%lu blocks so far\n",
4528                     (u_longlong_t)zb->zb_objset,
4529                     (u_longlong_t)BP_GET_FILL(bp),
4530                     avl_numnodes(t));
4531         }
4532
4533         if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
4534             BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
4535                 return (0);
4536
4537         ddt_key_fill(&zdde_search.zdde_key, bp);
4538
4539         zdde = avl_find(t, &zdde_search, &where);
4540
4541         if (zdde == NULL) {
4542                 zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
4543                 zdde->zdde_key = zdde_search.zdde_key;
4544                 avl_insert(t, zdde, where);
4545         }
4546
4547         zdde->zdde_ref_blocks += 1;
4548         zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
4549         zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
4550         zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
4551
4552         return (0);
4553 }
4554
4555 static void
4556 dump_simulated_ddt(spa_t *spa)
4557 {
4558         avl_tree_t t;
4559         void *cookie = NULL;
4560         zdb_ddt_entry_t *zdde;
4561         ddt_histogram_t ddh_total;
4562         ddt_stat_t dds_total;
4563
4564         bzero(&ddh_total, sizeof (ddh_total));
4565         bzero(&dds_total, sizeof (dds_total));
4566         avl_create(&t, ddt_entry_compare,
4567             sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
4568
4569         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4570
4571         (void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
4572             TRAVERSE_NO_DECRYPT, zdb_ddt_add_cb, &t);
4573
4574         spa_config_exit(spa, SCL_CONFIG, FTAG);
4575
4576         while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
4577                 ddt_stat_t dds;
4578                 uint64_t refcnt = zdde->zdde_ref_blocks;
4579                 ASSERT(refcnt != 0);
4580
4581                 dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
4582                 dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
4583                 dds.dds_psize = zdde->zdde_ref_psize / refcnt;
4584                 dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
4585
4586                 dds.dds_ref_blocks = zdde->zdde_ref_blocks;
4587                 dds.dds_ref_lsize = zdde->zdde_ref_lsize;
4588                 dds.dds_ref_psize = zdde->zdde_ref_psize;
4589                 dds.dds_ref_dsize = zdde->zdde_ref_dsize;
4590
4591                 ddt_stat_add(&ddh_total.ddh_stat[highbit64(refcnt) - 1],
4592                     &dds, 0);
4593
4594                 umem_free(zdde, sizeof (*zdde));
4595         }
4596
4597         avl_destroy(&t);
4598
4599         ddt_histogram_stat(&dds_total, &ddh_total);
4600
4601         (void) printf("Simulated DDT histogram:\n");
4602
4603         zpool_dump_ddt(&dds_total, &ddh_total);
4604
4605         dump_dedup_ratio(&dds_total);
4606 }
4607
4608 static int
4609 verify_device_removal_feature_counts(spa_t *spa)
4610 {
4611         uint64_t dr_feature_refcount = 0;
4612         uint64_t oc_feature_refcount = 0;
4613         uint64_t indirect_vdev_count = 0;
4614         uint64_t precise_vdev_count = 0;
4615         uint64_t obsolete_counts_object_count = 0;
4616         uint64_t obsolete_sm_count = 0;
4617         uint64_t obsolete_counts_count = 0;
4618         uint64_t scip_count = 0;
4619         uint64_t obsolete_bpobj_count = 0;
4620         int ret = 0;
4621
4622         spa_condensing_indirect_phys_t *scip =
4623             &spa->spa_condensing_indirect_phys;
4624         if (scip->scip_next_mapping_object != 0) {
4625                 vdev_t *vd = spa->spa_root_vdev->vdev_child[scip->scip_vdev];
4626                 ASSERT(scip->scip_prev_obsolete_sm_object != 0);
4627                 ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
4628
4629                 (void) printf("Condensing indirect vdev %llu: new mapping "
4630                     "object %llu, prev obsolete sm %llu\n",
4631                     (u_longlong_t)scip->scip_vdev,
4632                     (u_longlong_t)scip->scip_next_mapping_object,
4633                     (u_longlong_t)scip->scip_prev_obsolete_sm_object);
4634                 if (scip->scip_prev_obsolete_sm_object != 0) {
4635                         space_map_t *prev_obsolete_sm = NULL;
4636                         VERIFY0(space_map_open(&prev_obsolete_sm,
4637                             spa->spa_meta_objset,
4638                             scip->scip_prev_obsolete_sm_object,
4639                             0, vd->vdev_asize, 0));
4640                         space_map_update(prev_obsolete_sm);
4641                         dump_spacemap(spa->spa_meta_objset, prev_obsolete_sm);
4642                         (void) printf("\n");
4643                         space_map_close(prev_obsolete_sm);
4644                 }
4645
4646                 scip_count += 2;
4647         }
4648
4649         for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
4650                 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
4651                 vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
4652
4653                 if (vic->vic_mapping_object != 0) {
4654                         ASSERT(vd->vdev_ops == &vdev_indirect_ops ||
4655                             vd->vdev_removing);
4656                         indirect_vdev_count++;
4657
4658                         if (vd->vdev_indirect_mapping->vim_havecounts) {
4659                                 obsolete_counts_count++;
4660                         }
4661                 }
4662
4663                 boolean_t are_precise;
4664                 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
4665                 if (are_precise) {
4666                         ASSERT(vic->vic_mapping_object != 0);
4667                         precise_vdev_count++;
4668                 }
4669
4670                 uint64_t obsolete_sm_object;
4671                 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
4672                 if (obsolete_sm_object != 0) {
4673                         ASSERT(vic->vic_mapping_object != 0);
4674                         obsolete_sm_count++;
4675                 }
4676         }
4677
4678         (void) feature_get_refcount(spa,
4679             &spa_feature_table[SPA_FEATURE_DEVICE_REMOVAL],
4680             &dr_feature_refcount);
4681         (void) feature_get_refcount(spa,
4682             &spa_feature_table[SPA_FEATURE_OBSOLETE_COUNTS],
4683             &oc_feature_refcount);
4684
4685         if (dr_feature_refcount != indirect_vdev_count) {
4686                 ret = 1;
4687                 (void) printf("Number of indirect vdevs (%llu) " \
4688                     "does not match feature count (%llu)\n",
4689                     (u_longlong_t)indirect_vdev_count,
4690                     (u_longlong_t)dr_feature_refcount);
4691         } else {
4692                 (void) printf("Verified device_removal feature refcount " \
4693                     "of %llu is correct\n",
4694                     (u_longlong_t)dr_feature_refcount);
4695         }
4696
4697         if (zap_contains(spa_meta_objset(spa), DMU_POOL_DIRECTORY_OBJECT,
4698             DMU_POOL_OBSOLETE_BPOBJ) == 0) {
4699                 obsolete_bpobj_count++;
4700         }
4701
4702
4703         obsolete_counts_object_count = precise_vdev_count;
4704         obsolete_counts_object_count += obsolete_sm_count;
4705         obsolete_counts_object_count += obsolete_counts_count;
4706         obsolete_counts_object_count += scip_count;
4707         obsolete_counts_object_count += obsolete_bpobj_count;
4708         obsolete_counts_object_count += remap_deadlist_count;
4709
4710         if (oc_feature_refcount != obsolete_counts_object_count) {
4711                 ret = 1;
4712                 (void) printf("Number of obsolete counts objects (%llu) " \
4713                     "does not match feature count (%llu)\n",
4714                     (u_longlong_t)obsolete_counts_object_count,
4715                     (u_longlong_t)oc_feature_refcount);
4716                 (void) printf("pv:%llu os:%llu oc:%llu sc:%llu "
4717                     "ob:%llu rd:%llu\n",
4718                     (u_longlong_t)precise_vdev_count,
4719                     (u_longlong_t)obsolete_sm_count,
4720                     (u_longlong_t)obsolete_counts_count,
4721                     (u_longlong_t)scip_count,
4722                     (u_longlong_t)obsolete_bpobj_count,
4723                     (u_longlong_t)remap_deadlist_count);
4724         } else {
4725                 (void) printf("Verified indirect_refcount feature refcount " \
4726                     "of %llu is correct\n",
4727                     (u_longlong_t)oc_feature_refcount);
4728         }
4729         return (ret);
4730 }
4731
4732 static void
4733 zdb_set_skip_mmp(char *target)
4734 {
4735         spa_t *spa;
4736
4737         /*
4738          * Disable the activity check to allow examination of
4739          * active pools.
4740          */
4741         mutex_enter(&spa_namespace_lock);
4742         if ((spa = spa_lookup(target)) != NULL) {
4743                 spa->spa_import_flags |= ZFS_IMPORT_SKIP_MMP;
4744         }
4745         mutex_exit(&spa_namespace_lock);
4746 }
4747
4748 #define BOGUS_SUFFIX "_CHECKPOINTED_UNIVERSE"
4749 /*
4750  * Import the checkpointed state of the pool specified by the target
4751  * parameter as readonly. The function also accepts a pool config
4752  * as an optional parameter, else it attempts to infer the config by
4753  * the name of the target pool.
4754  *
4755  * Note that the checkpointed state's pool name will be the name of
4756  * the original pool with the above suffix appened to it. In addition,
4757  * if the target is not a pool name (e.g. a path to a dataset) then
4758  * the new_path parameter is populated with the updated path to
4759  * reflect the fact that we are looking into the checkpointed state.
4760  *
4761  * The function returns a newly-allocated copy of the name of the
4762  * pool containing the checkpointed state. When this copy is no
4763  * longer needed it should be freed with free(3C). Same thing
4764  * applies to the new_path parameter if allocated.
4765  */
4766 static char *
4767 import_checkpointed_state(char *target, nvlist_t *cfg, char **new_path)
4768 {
4769         int error = 0;
4770         char *poolname, *bogus_name = NULL;
4771
4772         /* If the target is not a pool, the extract the pool name */
4773         char *path_start = strchr(target, '/');
4774         if (path_start != NULL) {
4775                 size_t poolname_len = path_start - target;
4776                 poolname = strndup(target, poolname_len);
4777         } else {
4778                 poolname = target;
4779         }
4780
4781         if (cfg == NULL) {
4782                 zdb_set_skip_mmp(poolname);
4783                 error = spa_get_stats(poolname, &cfg, NULL, 0);
4784                 if (error != 0) {
4785                         fatal("Tried to read config of pool \"%s\" but "
4786                             "spa_get_stats() failed with error %d\n",
4787                             poolname, error);
4788                 }
4789         }
4790
4791         if (asprintf(&bogus_name, "%s%s", poolname, BOGUS_SUFFIX) == -1)
4792                 return (NULL);
4793         fnvlist_add_string(cfg, ZPOOL_CONFIG_POOL_NAME, bogus_name);
4794
4795         error = spa_import(bogus_name, cfg, NULL,
4796             ZFS_IMPORT_MISSING_LOG | ZFS_IMPORT_CHECKPOINT |
4797             ZFS_IMPORT_SKIP_MMP);
4798         if (error != 0) {
4799                 fatal("Tried to import pool \"%s\" but spa_import() failed "
4800                     "with error %d\n", bogus_name, error);
4801         }
4802
4803         if (new_path != NULL && path_start != NULL) {
4804                 if (asprintf(new_path, "%s%s", bogus_name, path_start) == -1) {
4805                         if (path_start != NULL)
4806                                 free(poolname);
4807                         return (NULL);
4808                 }
4809         }
4810
4811         if (target != poolname)
4812                 free(poolname);
4813
4814         return (bogus_name);
4815 }
4816
4817 typedef struct verify_checkpoint_sm_entry_cb_arg {
4818         vdev_t *vcsec_vd;
4819
4820         /* the following fields are only used for printing progress */
4821         uint64_t vcsec_entryid;
4822         uint64_t vcsec_num_entries;
4823 } verify_checkpoint_sm_entry_cb_arg_t;
4824
4825 #define ENTRIES_PER_PROGRESS_UPDATE 10000
4826
4827 static int
4828 verify_checkpoint_sm_entry_cb(space_map_entry_t *sme, void *arg)
4829 {
4830         verify_checkpoint_sm_entry_cb_arg_t *vcsec = arg;
4831         vdev_t *vd = vcsec->vcsec_vd;
4832         metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
4833         uint64_t end = sme->sme_offset + sme->sme_run;
4834
4835         ASSERT(sme->sme_type == SM_FREE);
4836
4837         if ((vcsec->vcsec_entryid % ENTRIES_PER_PROGRESS_UPDATE) == 0) {
4838                 (void) fprintf(stderr,
4839                     "\rverifying vdev %llu, space map entry %llu of %llu ...",
4840                     (longlong_t)vd->vdev_id,
4841                     (longlong_t)vcsec->vcsec_entryid,
4842                     (longlong_t)vcsec->vcsec_num_entries);
4843         }
4844         vcsec->vcsec_entryid++;
4845
4846         /*
4847          * See comment in checkpoint_sm_exclude_entry_cb()
4848          */
4849         VERIFY3U(sme->sme_offset, >=, ms->ms_start);
4850         VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
4851
4852         /*
4853          * The entries in the vdev_checkpoint_sm should be marked as
4854          * allocated in the checkpointed state of the pool, therefore
4855          * their respective ms_allocateable trees should not contain them.
4856          */
4857         mutex_enter(&ms->ms_lock);
4858         range_tree_verify(ms->ms_allocatable, sme->sme_offset, sme->sme_run);
4859         mutex_exit(&ms->ms_lock);
4860
4861         return (0);
4862 }
4863
4864 /*
4865  * Verify that all segments in the vdev_checkpoint_sm are allocated
4866  * according to the checkpoint's ms_sm (i.e. are not in the checkpoint's
4867  * ms_allocatable).
4868  *
4869  * Do so by comparing the checkpoint space maps (vdev_checkpoint_sm) of
4870  * each vdev in the current state of the pool to the metaslab space maps
4871  * (ms_sm) of the checkpointed state of the pool.
4872  *
4873  * Note that the function changes the state of the ms_allocatable
4874  * trees of the current spa_t. The entries of these ms_allocatable
4875  * trees are cleared out and then repopulated from with the free
4876  * entries of their respective ms_sm space maps.
4877  */
4878 static void
4879 verify_checkpoint_vdev_spacemaps(spa_t *checkpoint, spa_t *current)
4880 {
4881         vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
4882         vdev_t *current_rvd = current->spa_root_vdev;
4883
4884         load_concrete_ms_allocatable_trees(checkpoint, SM_FREE);
4885
4886         for (uint64_t c = 0; c < ckpoint_rvd->vdev_children; c++) {
4887                 vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[c];
4888                 vdev_t *current_vd = current_rvd->vdev_child[c];
4889
4890                 space_map_t *checkpoint_sm = NULL;
4891                 uint64_t checkpoint_sm_obj;
4892
4893                 if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
4894                         /*
4895                          * Since we don't allow device removal in a pool
4896                          * that has a checkpoint, we expect that all removed
4897                          * vdevs were removed from the pool before the
4898                          * checkpoint.
4899                          */
4900                         ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
4901                         continue;
4902                 }
4903
4904                 /*
4905                  * If the checkpoint space map doesn't exist, then nothing
4906                  * here is checkpointed so there's nothing to verify.
4907                  */
4908                 if (current_vd->vdev_top_zap == 0 ||
4909                     zap_contains(spa_meta_objset(current),
4910                     current_vd->vdev_top_zap,
4911                     VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
4912                         continue;
4913
4914                 VERIFY0(zap_lookup(spa_meta_objset(current),
4915                     current_vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
4916                     sizeof (uint64_t), 1, &checkpoint_sm_obj));
4917
4918                 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(current),
4919                     checkpoint_sm_obj, 0, current_vd->vdev_asize,
4920                     current_vd->vdev_ashift));
4921                 space_map_update(checkpoint_sm);
4922
4923                 verify_checkpoint_sm_entry_cb_arg_t vcsec;
4924                 vcsec.vcsec_vd = ckpoint_vd;
4925                 vcsec.vcsec_entryid = 0;
4926                 vcsec.vcsec_num_entries =
4927                     space_map_length(checkpoint_sm) / sizeof (uint64_t);
4928                 VERIFY0(space_map_iterate(checkpoint_sm,
4929                     verify_checkpoint_sm_entry_cb, &vcsec));
4930                 if (dump_opt['m'] > 3)
4931                         dump_spacemap(current->spa_meta_objset, checkpoint_sm);
4932                 space_map_close(checkpoint_sm);
4933         }
4934
4935         /*
4936          * If we've added vdevs since we took the checkpoint, ensure
4937          * that their checkpoint space maps are empty.
4938          */
4939         if (ckpoint_rvd->vdev_children < current_rvd->vdev_children) {
4940                 for (uint64_t c = ckpoint_rvd->vdev_children;
4941                     c < current_rvd->vdev_children; c++) {
4942                         vdev_t *current_vd = current_rvd->vdev_child[c];
4943                         ASSERT3P(current_vd->vdev_checkpoint_sm, ==, NULL);
4944                 }
4945         }
4946
4947         /* for cleaner progress output */
4948         (void) fprintf(stderr, "\n");
4949 }
4950
4951 /*
4952  * Verifies that all space that's allocated in the checkpoint is
4953  * still allocated in the current version, by checking that everything
4954  * in checkpoint's ms_allocatable (which is actually allocated, not
4955  * allocatable/free) is not present in current's ms_allocatable.
4956  *
4957  * Note that the function changes the state of the ms_allocatable
4958  * trees of both spas when called. The entries of all ms_allocatable
4959  * trees are cleared out and then repopulated from their respective
4960  * ms_sm space maps. In the checkpointed state we load the allocated
4961  * entries, and in the current state we load the free entries.
4962  */
4963 static void
4964 verify_checkpoint_ms_spacemaps(spa_t *checkpoint, spa_t *current)
4965 {
4966         vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
4967         vdev_t *current_rvd = current->spa_root_vdev;
4968
4969         load_concrete_ms_allocatable_trees(checkpoint, SM_ALLOC);
4970         load_concrete_ms_allocatable_trees(current, SM_FREE);
4971
4972         for (uint64_t i = 0; i < ckpoint_rvd->vdev_children; i++) {
4973                 vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[i];
4974                 vdev_t *current_vd = current_rvd->vdev_child[i];
4975
4976                 if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
4977                         /*
4978                          * See comment in verify_checkpoint_vdev_spacemaps()
4979                          */
4980                         ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
4981                         continue;
4982                 }
4983
4984                 for (uint64_t m = 0; m < ckpoint_vd->vdev_ms_count; m++) {
4985                         metaslab_t *ckpoint_msp = ckpoint_vd->vdev_ms[m];
4986                         metaslab_t *current_msp = current_vd->vdev_ms[m];
4987
4988                         (void) fprintf(stderr,
4989                             "\rverifying vdev %llu of %llu, "
4990                             "metaslab %llu of %llu ...",
4991                             (longlong_t)current_vd->vdev_id,
4992                             (longlong_t)current_rvd->vdev_children,
4993                             (longlong_t)current_vd->vdev_ms[m]->ms_id,
4994                             (longlong_t)current_vd->vdev_ms_count);
4995
4996                         /*
4997                          * We walk through the ms_allocatable trees that
4998                          * are loaded with the allocated blocks from the
4999                          * ms_sm spacemaps of the checkpoint. For each
5000                          * one of these ranges we ensure that none of them
5001                          * exists in the ms_allocatable trees of the
5002                          * current state which are loaded with the ranges
5003                          * that are currently free.
5004                          *
5005                          * This way we ensure that none of the blocks that
5006                          * are part of the checkpoint were freed by mistake.
5007                          */
5008                         range_tree_walk(ckpoint_msp->ms_allocatable,
5009                             (range_tree_func_t *)range_tree_verify,
5010                             current_msp->ms_allocatable);
5011                 }
5012         }
5013
5014         /* for cleaner progress output */
5015         (void) fprintf(stderr, "\n");
5016 }
5017
5018 static void
5019 verify_checkpoint_blocks(spa_t *spa)
5020 {
5021         spa_t *checkpoint_spa;
5022         char *checkpoint_pool;
5023         nvlist_t *config = NULL;
5024         int error = 0;
5025
5026         /*
5027          * We import the checkpointed state of the pool (under a different
5028          * name) so we can do verification on it against the current state
5029          * of the pool.
5030          */
5031         checkpoint_pool = import_checkpointed_state(spa->spa_name, config,
5032             NULL);
5033         ASSERT(strcmp(spa->spa_name, checkpoint_pool) != 0);
5034
5035         error = spa_open(checkpoint_pool, &checkpoint_spa, FTAG);
5036         if (error != 0) {
5037                 fatal("Tried to open pool \"%s\" but spa_open() failed with "
5038                     "error %d\n", checkpoint_pool, error);
5039         }
5040
5041         /*
5042          * Ensure that ranges in the checkpoint space maps of each vdev
5043          * are allocated according to the checkpointed state's metaslab
5044          * space maps.
5045          */
5046         verify_checkpoint_vdev_spacemaps(checkpoint_spa, spa);
5047
5048         /*
5049          * Ensure that allocated ranges in the checkpoint's metaslab
5050          * space maps remain allocated in the metaslab space maps of
5051          * the current state.
5052          */
5053         verify_checkpoint_ms_spacemaps(checkpoint_spa, spa);
5054
5055         /*
5056          * Once we are done, we get rid of the checkpointed state.
5057          */
5058         spa_close(checkpoint_spa, FTAG);
5059         free(checkpoint_pool);
5060 }
5061
5062 static void
5063 dump_leftover_checkpoint_blocks(spa_t *spa)
5064 {
5065         vdev_t *rvd = spa->spa_root_vdev;
5066
5067         for (uint64_t i = 0; i < rvd->vdev_children; i++) {
5068                 vdev_t *vd = rvd->vdev_child[i];
5069
5070                 space_map_t *checkpoint_sm = NULL;
5071                 uint64_t checkpoint_sm_obj;
5072
5073                 if (vd->vdev_top_zap == 0)
5074                         continue;
5075
5076                 if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
5077                     VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
5078                         continue;
5079
5080                 VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
5081                     VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
5082                     sizeof (uint64_t), 1, &checkpoint_sm_obj));
5083
5084                 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
5085                     checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
5086                 space_map_update(checkpoint_sm);
5087                 dump_spacemap(spa->spa_meta_objset, checkpoint_sm);
5088                 space_map_close(checkpoint_sm);
5089         }
5090 }
5091
5092 static int
5093 verify_checkpoint(spa_t *spa)
5094 {
5095         uberblock_t checkpoint;
5096         int error;
5097
5098         if (!spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT))
5099                 return (0);
5100
5101         error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
5102             DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
5103             sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
5104
5105         if (error == ENOENT && !dump_opt['L']) {
5106                 /*
5107                  * If the feature is active but the uberblock is missing
5108                  * then we must be in the middle of discarding the
5109                  * checkpoint.
5110                  */
5111                 (void) printf("\nPartially discarded checkpoint "
5112                     "state found:\n");
5113                 if (dump_opt['m'] > 3)
5114                         dump_leftover_checkpoint_blocks(spa);
5115                 return (0);
5116         } else if (error != 0) {
5117                 (void) printf("lookup error %d when looking for "
5118                     "checkpointed uberblock in MOS\n", error);
5119                 return (error);
5120         }
5121         dump_uberblock(&checkpoint, "\nCheckpointed uberblock found:\n", "\n");
5122
5123         if (checkpoint.ub_checkpoint_txg == 0) {
5124                 (void) printf("\nub_checkpoint_txg not set in checkpointed "
5125                     "uberblock\n");
5126                 error = 3;
5127         }
5128
5129         if (error == 0 && !dump_opt['L'])
5130                 verify_checkpoint_blocks(spa);
5131
5132         return (error);
5133 }
5134
5135 /* ARGSUSED */
5136 static void
5137 mos_leaks_cb(void *arg, uint64_t start, uint64_t size)
5138 {
5139         for (uint64_t i = start; i < size; i++) {
5140                 (void) printf("MOS object %llu referenced but not allocated\n",
5141                     (u_longlong_t)i);
5142         }
5143 }
5144
5145 static void
5146 mos_obj_refd(uint64_t obj)
5147 {
5148         if (obj != 0 && mos_refd_objs != NULL)
5149                 range_tree_add(mos_refd_objs, obj, 1);
5150 }
5151
5152 /*
5153  * Call on a MOS object that may already have been referenced.
5154  */
5155 static void
5156 mos_obj_refd_multiple(uint64_t obj)
5157 {
5158         if (obj != 0 && mos_refd_objs != NULL &&
5159             !range_tree_contains(mos_refd_objs, obj, 1))
5160                 range_tree_add(mos_refd_objs, obj, 1);
5161 }
5162
5163 static void
5164 mos_leak_vdev(vdev_t *vd)
5165 {
5166         mos_obj_refd(vd->vdev_dtl_object);
5167         mos_obj_refd(vd->vdev_ms_array);
5168         mos_obj_refd(vd->vdev_top_zap);
5169         mos_obj_refd(vd->vdev_indirect_config.vic_births_object);
5170         mos_obj_refd(vd->vdev_indirect_config.vic_mapping_object);
5171         mos_obj_refd(vd->vdev_leaf_zap);
5172         if (vd->vdev_checkpoint_sm != NULL)
5173                 mos_obj_refd(vd->vdev_checkpoint_sm->sm_object);
5174         if (vd->vdev_indirect_mapping != NULL) {
5175                 mos_obj_refd(vd->vdev_indirect_mapping->
5176                     vim_phys->vimp_counts_object);
5177         }
5178         if (vd->vdev_obsolete_sm != NULL)
5179                 mos_obj_refd(vd->vdev_obsolete_sm->sm_object);
5180
5181         for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
5182                 metaslab_t *ms = vd->vdev_ms[m];
5183                 mos_obj_refd(space_map_object(ms->ms_sm));
5184         }
5185
5186         for (uint64_t c = 0; c < vd->vdev_children; c++) {
5187                 mos_leak_vdev(vd->vdev_child[c]);
5188         }
5189 }
5190
5191 static int
5192 dump_mos_leaks(spa_t *spa)
5193 {
5194         int rv = 0;
5195         objset_t *mos = spa->spa_meta_objset;
5196         dsl_pool_t *dp = spa->spa_dsl_pool;
5197
5198         /* Visit and mark all referenced objects in the MOS */
5199
5200         mos_obj_refd(DMU_POOL_DIRECTORY_OBJECT);
5201         mos_obj_refd(spa->spa_pool_props_object);
5202         mos_obj_refd(spa->spa_config_object);
5203         mos_obj_refd(spa->spa_ddt_stat_object);
5204         mos_obj_refd(spa->spa_feat_desc_obj);
5205         mos_obj_refd(spa->spa_feat_enabled_txg_obj);
5206         mos_obj_refd(spa->spa_feat_for_read_obj);
5207         mos_obj_refd(spa->spa_feat_for_write_obj);
5208         mos_obj_refd(spa->spa_history);
5209         mos_obj_refd(spa->spa_errlog_last);
5210         mos_obj_refd(spa->spa_errlog_scrub);
5211         mos_obj_refd(spa->spa_all_vdev_zaps);
5212         mos_obj_refd(spa->spa_dsl_pool->dp_bptree_obj);
5213         mos_obj_refd(spa->spa_dsl_pool->dp_tmp_userrefs_obj);
5214         mos_obj_refd(spa->spa_dsl_pool->dp_scan->scn_phys.scn_queue_obj);
5215         bpobj_count_refd(&spa->spa_deferred_bpobj);
5216         mos_obj_refd(dp->dp_empty_bpobj);
5217         bpobj_count_refd(&dp->dp_obsolete_bpobj);
5218         bpobj_count_refd(&dp->dp_free_bpobj);
5219         mos_obj_refd(spa->spa_l2cache.sav_object);
5220         mos_obj_refd(spa->spa_spares.sav_object);
5221
5222         mos_obj_refd(spa->spa_condensing_indirect_phys.
5223             scip_next_mapping_object);
5224         mos_obj_refd(spa->spa_condensing_indirect_phys.
5225             scip_prev_obsolete_sm_object);
5226         if (spa->spa_condensing_indirect_phys.scip_next_mapping_object != 0) {
5227                 vdev_indirect_mapping_t *vim =
5228                     vdev_indirect_mapping_open(mos,
5229                     spa->spa_condensing_indirect_phys.scip_next_mapping_object);
5230                 mos_obj_refd(vim->vim_phys->vimp_counts_object);
5231                 vdev_indirect_mapping_close(vim);
5232         }
5233
5234         if (dp->dp_origin_snap != NULL) {
5235                 dsl_dataset_t *ds;
5236
5237                 dsl_pool_config_enter(dp, FTAG);
5238                 VERIFY0(dsl_dataset_hold_obj(dp,
5239                     dsl_dataset_phys(dp->dp_origin_snap)->ds_next_snap_obj,
5240                     FTAG, &ds));
5241                 count_ds_mos_objects(ds);
5242                 dump_deadlist(&ds->ds_deadlist);
5243                 dsl_dataset_rele(ds, FTAG);
5244                 dsl_pool_config_exit(dp, FTAG);
5245
5246                 count_ds_mos_objects(dp->dp_origin_snap);
5247                 dump_deadlist(&dp->dp_origin_snap->ds_deadlist);
5248         }
5249         count_dir_mos_objects(dp->dp_mos_dir);
5250         if (dp->dp_free_dir != NULL)
5251                 count_dir_mos_objects(dp->dp_free_dir);
5252         if (dp->dp_leak_dir != NULL)
5253                 count_dir_mos_objects(dp->dp_leak_dir);
5254
5255         mos_leak_vdev(spa->spa_root_vdev);
5256
5257         for (uint64_t class = 0; class < DDT_CLASSES; class++) {
5258                 for (uint64_t type = 0; type < DDT_TYPES; type++) {
5259                         for (uint64_t cksum = 0;
5260                             cksum < ZIO_CHECKSUM_FUNCTIONS; cksum++) {
5261                                 ddt_t *ddt = spa->spa_ddt[cksum];
5262                                 mos_obj_refd(ddt->ddt_object[type][class]);
5263                         }
5264                 }
5265         }
5266
5267         /*
5268          * Visit all allocated objects and make sure they are referenced.
5269          */
5270         uint64_t object = 0;
5271         while (dmu_object_next(mos, &object, B_FALSE, 0) == 0) {
5272                 if (range_tree_contains(mos_refd_objs, object, 1)) {
5273                         range_tree_remove(mos_refd_objs, object, 1);
5274                 } else {
5275                         dmu_object_info_t doi;
5276                         const char *name;
5277                         dmu_object_info(mos, object, &doi);
5278                         if (doi.doi_type & DMU_OT_NEWTYPE) {
5279                                 dmu_object_byteswap_t bswap =
5280                                     DMU_OT_BYTESWAP(doi.doi_type);
5281                                 name = dmu_ot_byteswap[bswap].ob_name;
5282                         } else {
5283                                 name = dmu_ot[doi.doi_type].ot_name;
5284                         }
5285
5286                         (void) printf("MOS object %llu (%s) leaked\n",
5287                             (u_longlong_t)object, name);
5288                         rv = 2;
5289                 }
5290         }
5291         (void) range_tree_walk(mos_refd_objs, mos_leaks_cb, NULL);
5292         if (!range_tree_is_empty(mos_refd_objs))
5293                 rv = 2;
5294         range_tree_vacate(mos_refd_objs, NULL, NULL);
5295         range_tree_destroy(mos_refd_objs);
5296         return (rv);
5297 }
5298
5299 static void
5300 dump_zpool(spa_t *spa)
5301 {
5302         dsl_pool_t *dp = spa_get_dsl(spa);
5303         int rc = 0;
5304
5305         if (dump_opt['S']) {
5306                 dump_simulated_ddt(spa);
5307                 return;
5308         }
5309
5310         if (!dump_opt['e'] && dump_opt['C'] > 1) {
5311                 (void) printf("\nCached configuration:\n");
5312                 dump_nvlist(spa->spa_config, 8);
5313         }
5314
5315         if (dump_opt['C'])
5316                 dump_config(spa);
5317
5318         if (dump_opt['u'])
5319                 dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
5320
5321         if (dump_opt['D'])
5322                 dump_all_ddts(spa);
5323
5324         if (dump_opt['d'] > 2 || dump_opt['m'])
5325                 dump_metaslabs(spa);
5326         if (dump_opt['M'])
5327                 dump_metaslab_groups(spa);
5328
5329         if (dump_opt['d'] || dump_opt['i']) {
5330                 spa_feature_t f;
5331                 mos_refd_objs = range_tree_create(NULL, NULL);
5332                 dump_dir(dp->dp_meta_objset);
5333
5334                 if (dump_opt['d'] >= 3) {
5335                         dsl_pool_t *dp = spa->spa_dsl_pool;
5336                         dump_full_bpobj(&spa->spa_deferred_bpobj,
5337                             "Deferred frees", 0);
5338                         if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
5339                                 dump_full_bpobj(&dp->dp_free_bpobj,
5340                                     "Pool snapshot frees", 0);
5341                         }
5342                         if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
5343                                 ASSERT(spa_feature_is_enabled(spa,
5344                                     SPA_FEATURE_DEVICE_REMOVAL));
5345                                 dump_full_bpobj(&dp->dp_obsolete_bpobj,
5346                                     "Pool obsolete blocks", 0);
5347                         }
5348
5349                         if (spa_feature_is_active(spa,
5350                             SPA_FEATURE_ASYNC_DESTROY)) {
5351                                 dump_bptree(spa->spa_meta_objset,
5352                                     dp->dp_bptree_obj,
5353                                     "Pool dataset frees");
5354                         }
5355                         dump_dtl(spa->spa_root_vdev, 0);
5356                 }
5357                 (void) dmu_objset_find(spa_name(spa), dump_one_dir,
5358                     NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
5359
5360                 if (rc == 0 && !dump_opt['L'])
5361                         rc = dump_mos_leaks(spa);
5362
5363                 for (f = 0; f < SPA_FEATURES; f++) {
5364                         uint64_t refcount;
5365
5366                         if (!(spa_feature_table[f].fi_flags &
5367                             ZFEATURE_FLAG_PER_DATASET) ||
5368                             !spa_feature_is_enabled(spa, f)) {
5369                                 ASSERT0(dataset_feature_count[f]);
5370                                 continue;
5371                         }
5372                         if (feature_get_refcount(spa, &spa_feature_table[f],
5373                             &refcount) == ENOTSUP)
5374                                 continue;
5375                         if (dataset_feature_count[f] != refcount) {
5376                                 (void) printf("%s feature refcount mismatch: "
5377                                     "%lld datasets != %lld refcount\n",
5378                                     spa_feature_table[f].fi_uname,
5379                                     (longlong_t)dataset_feature_count[f],
5380                                     (longlong_t)refcount);
5381                                 rc = 2;
5382                         } else {
5383                                 (void) printf("Verified %s feature refcount "
5384                                     "of %llu is correct\n",
5385                                     spa_feature_table[f].fi_uname,
5386                                     (longlong_t)refcount);
5387                         }
5388                 }
5389
5390                 if (rc == 0) {
5391                         rc = verify_device_removal_feature_counts(spa);
5392                 }
5393         }
5394
5395         if (rc == 0 && (dump_opt['b'] || dump_opt['c']))
5396                 rc = dump_block_stats(spa);
5397
5398         if (rc == 0)
5399                 rc = verify_spacemap_refcounts(spa);
5400
5401         if (dump_opt['s'])
5402                 show_pool_stats(spa);
5403
5404         if (dump_opt['h'])
5405                 dump_history(spa);
5406
5407         if (rc == 0)
5408                 rc = verify_checkpoint(spa);
5409
5410         if (rc != 0) {
5411                 dump_debug_buffer();
5412                 exit(rc);
5413         }
5414 }
5415
5416 #define ZDB_FLAG_CHECKSUM       0x0001
5417 #define ZDB_FLAG_DECOMPRESS     0x0002
5418 #define ZDB_FLAG_BSWAP          0x0004
5419 #define ZDB_FLAG_GBH            0x0008
5420 #define ZDB_FLAG_INDIRECT       0x0010
5421 #define ZDB_FLAG_PHYS           0x0020
5422 #define ZDB_FLAG_RAW            0x0040
5423 #define ZDB_FLAG_PRINT_BLKPTR   0x0080
5424
5425 static int flagbits[256];
5426
5427 static void
5428 zdb_print_blkptr(blkptr_t *bp, int flags)
5429 {
5430         char blkbuf[BP_SPRINTF_LEN];
5431
5432         if (flags & ZDB_FLAG_BSWAP)
5433                 byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
5434
5435         snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
5436         (void) printf("%s\n", blkbuf);
5437 }
5438
5439 static void
5440 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
5441 {
5442         int i;
5443
5444         for (i = 0; i < nbps; i++)
5445                 zdb_print_blkptr(&bp[i], flags);
5446 }
5447
5448 static void
5449 zdb_dump_gbh(void *buf, int flags)
5450 {
5451         zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
5452 }
5453
5454 static void
5455 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
5456 {
5457         if (flags & ZDB_FLAG_BSWAP)
5458                 byteswap_uint64_array(buf, size);
5459         VERIFY(write(fileno(stdout), buf, size) == size);
5460 }
5461
5462 static void
5463 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
5464 {
5465         uint64_t *d = (uint64_t *)buf;
5466         unsigned nwords = size / sizeof (uint64_t);
5467         int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
5468         unsigned i, j;
5469         const char *hdr;
5470         char *c;
5471
5472
5473         if (do_bswap)
5474                 hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
5475         else
5476                 hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
5477
5478         (void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
5479
5480 #ifdef _LITTLE_ENDIAN
5481         /* correct the endianness */
5482         do_bswap = !do_bswap;
5483 #endif
5484         for (i = 0; i < nwords; i += 2) {
5485                 (void) printf("%06llx:  %016llx  %016llx  ",
5486                     (u_longlong_t)(i * sizeof (uint64_t)),
5487                     (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
5488                     (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
5489
5490                 c = (char *)&d[i];
5491                 for (j = 0; j < 2 * sizeof (uint64_t); j++)
5492                         (void) printf("%c", isprint(c[j]) ? c[j] : '.');
5493                 (void) printf("\n");
5494         }
5495 }
5496
5497 /*
5498  * There are two acceptable formats:
5499  *      leaf_name         - For example: c1t0d0 or /tmp/ztest.0a
5500  *      child[.child]*    - For example: 0.1.1
5501  *
5502  * The second form can be used to specify arbitrary vdevs anywhere
5503  * in the hierarchy.  For example, in a pool with a mirror of
5504  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
5505  */
5506 static vdev_t *
5507 zdb_vdev_lookup(vdev_t *vdev, const char *path)
5508 {
5509         char *s, *p, *q;
5510         unsigned i;
5511
5512         if (vdev == NULL)
5513                 return (NULL);
5514
5515         /* First, assume the x.x.x.x format */
5516         i = strtoul(path, &s, 10);
5517         if (s == path || (s && *s != '.' && *s != '\0'))
5518                 goto name;
5519         if (i >= vdev->vdev_children)
5520                 return (NULL);
5521
5522         vdev = vdev->vdev_child[i];
5523         if (s && *s == '\0')
5524                 return (vdev);
5525         return (zdb_vdev_lookup(vdev, s+1));
5526
5527 name:
5528         for (i = 0; i < vdev->vdev_children; i++) {
5529                 vdev_t *vc = vdev->vdev_child[i];
5530
5531                 if (vc->vdev_path == NULL) {
5532                         vc = zdb_vdev_lookup(vc, path);
5533                         if (vc == NULL)
5534                                 continue;
5535                         else
5536                                 return (vc);
5537                 }
5538
5539                 p = strrchr(vc->vdev_path, '/');
5540                 p = p ? p + 1 : vc->vdev_path;
5541                 q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
5542
5543                 if (strcmp(vc->vdev_path, path) == 0)
5544                         return (vc);
5545                 if (strcmp(p, path) == 0)
5546                         return (vc);
5547                 if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
5548                         return (vc);
5549         }
5550
5551         return (NULL);
5552 }
5553
5554 /*
5555  * Read a block from a pool and print it out.  The syntax of the
5556  * block descriptor is:
5557  *
5558  *      pool:vdev_specifier:offset:size[:flags]
5559  *
5560  *      pool           - The name of the pool you wish to read from
5561  *      vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
5562  *      offset         - offset, in hex, in bytes
5563  *      size           - Amount of data to read, in hex, in bytes
5564  *      flags          - A string of characters specifying options
5565  *               b: Decode a blkptr at given offset within block
5566  *              *c: Calculate and display checksums
5567  *               d: Decompress data before dumping
5568  *               e: Byteswap data before dumping
5569  *               g: Display data as a gang block header
5570  *               i: Display as an indirect block
5571  *               p: Do I/O to physical offset
5572  *               r: Dump raw data to stdout
5573  *
5574  *              * = not yet implemented
5575  */
5576 static void
5577 zdb_read_block(char *thing, spa_t *spa)
5578 {
5579         blkptr_t blk, *bp = &blk;
5580         dva_t *dva = bp->blk_dva;
5581         int flags = 0;
5582         uint64_t offset = 0, size = 0, psize = 0, lsize = 0, blkptr_offset = 0;
5583         zio_t *zio;
5584         vdev_t *vd;
5585         abd_t *pabd;
5586         void *lbuf, *buf;
5587         const char *s, *vdev;
5588         char *p, *dup, *flagstr;
5589         int i, error;
5590         boolean_t borrowed = B_FALSE;
5591
5592         dup = strdup(thing);
5593         s = strtok(dup, ":");
5594         vdev = s ? s : "";
5595         s = strtok(NULL, ":");
5596         offset = strtoull(s ? s : "", NULL, 16);
5597         s = strtok(NULL, ":");
5598         size = strtoull(s ? s : "", NULL, 16);
5599         s = strtok(NULL, ":");
5600         if (s)
5601                 flagstr = strdup(s);
5602         else
5603                 flagstr = strdup("");
5604
5605         s = NULL;
5606         if (size == 0)
5607                 s = "size must not be zero";
5608         if (!IS_P2ALIGNED(size, DEV_BSIZE))
5609                 s = "size must be a multiple of sector size";
5610         if (!IS_P2ALIGNED(offset, DEV_BSIZE))
5611                 s = "offset must be a multiple of sector size";
5612         if (s) {
5613                 (void) printf("Invalid block specifier: %s  - %s\n", thing, s);
5614                 free(flagstr);
5615                 free(dup);
5616                 return;
5617         }
5618
5619         for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
5620                 for (i = 0; flagstr[i]; i++) {
5621                         int bit = flagbits[(uchar_t)flagstr[i]];
5622
5623                         if (bit == 0) {
5624                                 (void) printf("***Invalid flag: %c\n",
5625                                     flagstr[i]);
5626                                 continue;
5627                         }
5628                         flags |= bit;
5629
5630                         /* If it's not something with an argument, keep going */
5631                         if ((bit & (ZDB_FLAG_CHECKSUM |
5632                             ZDB_FLAG_PRINT_BLKPTR)) == 0)
5633                                 continue;
5634
5635                         p = &flagstr[i + 1];
5636                         if (bit == ZDB_FLAG_PRINT_BLKPTR) {
5637                                 blkptr_offset = strtoull(p, &p, 16);
5638                                 i = p - &flagstr[i + 1];
5639                         }
5640                         if (*p != ':' && *p != '\0') {
5641                                 (void) printf("***Invalid flag arg: '%s'\n", s);
5642                                 free(flagstr);
5643                                 free(dup);
5644                                 return;
5645                         }
5646                 }
5647         }
5648         free(flagstr);
5649
5650         vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
5651         if (vd == NULL) {
5652                 (void) printf("***Invalid vdev: %s\n", vdev);
5653                 free(dup);
5654                 return;
5655         } else {
5656                 if (vd->vdev_path)
5657                         (void) fprintf(stderr, "Found vdev: %s\n",
5658                             vd->vdev_path);
5659                 else
5660                         (void) fprintf(stderr, "Found vdev type: %s\n",
5661                             vd->vdev_ops->vdev_op_type);
5662         }
5663
5664         psize = size;
5665         lsize = size;
5666
5667         pabd = abd_alloc_for_io(SPA_MAXBLOCKSIZE, B_FALSE);
5668         lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
5669
5670         BP_ZERO(bp);
5671
5672         DVA_SET_VDEV(&dva[0], vd->vdev_id);
5673         DVA_SET_OFFSET(&dva[0], offset);
5674         DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
5675         DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
5676
5677         BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
5678
5679         BP_SET_LSIZE(bp, lsize);
5680         BP_SET_PSIZE(bp, psize);
5681         BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
5682         BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
5683         BP_SET_TYPE(bp, DMU_OT_NONE);
5684         BP_SET_LEVEL(bp, 0);
5685         BP_SET_DEDUP(bp, 0);
5686         BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
5687
5688         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
5689         zio = zio_root(spa, NULL, NULL, 0);
5690
5691         if (vd == vd->vdev_top) {
5692                 /*
5693                  * Treat this as a normal block read.
5694                  */
5695                 zio_nowait(zio_read(zio, spa, bp, pabd, psize, NULL, NULL,
5696                     ZIO_PRIORITY_SYNC_READ,
5697                     ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
5698         } else {
5699                 /*
5700                  * Treat this as a vdev child I/O.
5701                  */
5702                 zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pabd,
5703                     psize, ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
5704                     ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
5705                     ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
5706                     ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW | ZIO_FLAG_OPTIONAL,
5707                     NULL, NULL));
5708         }
5709
5710         error = zio_wait(zio);
5711         spa_config_exit(spa, SCL_STATE, FTAG);
5712
5713         if (error) {
5714                 (void) printf("Read of %s failed, error: %d\n", thing, error);
5715                 goto out;
5716         }
5717
5718         if (flags & ZDB_FLAG_DECOMPRESS) {
5719                 /*
5720                  * We don't know how the data was compressed, so just try
5721                  * every decompress function at every inflated blocksize.
5722                  */
5723                 enum zio_compress c;
5724                 void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
5725
5726                 /*
5727                  * XXX - On the one hand, with SPA_MAXBLOCKSIZE at 16MB,
5728                  * this could take a while and we should let the user know
5729                  * we are not stuck.  On the other hand, printing progress
5730                  * info gets old after a while.  What to do?
5731                  */
5732                 for (lsize = psize + SPA_MINBLOCKSIZE;
5733                     lsize <= SPA_MAXBLOCKSIZE; lsize += SPA_MINBLOCKSIZE) {
5734                         for (c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++) {
5735                                 /*
5736                                  * ZLE can easily decompress non zle stream.
5737                                  * So have an option to disable it.
5738                                  */
5739                                 if (c == ZIO_COMPRESS_ZLE &&
5740                                     getenv("ZDB_NO_ZLE"))
5741                                         continue;
5742
5743                                 (void) fprintf(stderr,
5744                                     "Trying %05llx -> %05llx (%s)\n",
5745                                     (u_longlong_t)psize, (u_longlong_t)lsize,
5746                                     zio_compress_table[c].ci_name);
5747
5748                                 /*
5749                                  * We randomize lbuf2, and decompress to both
5750                                  * lbuf and lbuf2. This way, we will know if
5751                                  * decompression fill exactly to lsize.
5752                                  */
5753                                 VERIFY0(random_get_pseudo_bytes(lbuf2, lsize));
5754
5755                                 if (zio_decompress_data(c, pabd,
5756                                     lbuf, psize, lsize) == 0 &&
5757                                     zio_decompress_data(c, pabd,
5758                                     lbuf2, psize, lsize) == 0 &&
5759                                     bcmp(lbuf, lbuf2, lsize) == 0)
5760                                         break;
5761                         }
5762                         if (c != ZIO_COMPRESS_FUNCTIONS)
5763                                 break;
5764                 }
5765                 umem_free(lbuf2, SPA_MAXBLOCKSIZE);
5766
5767                 if (lsize > SPA_MAXBLOCKSIZE) {
5768                         (void) printf("Decompress of %s failed\n", thing);
5769                         goto out;
5770                 }
5771                 buf = lbuf;
5772                 size = lsize;
5773         } else {
5774                 size = psize;
5775                 buf = abd_borrow_buf_copy(pabd, size);
5776                 borrowed = B_TRUE;
5777         }
5778
5779         if (flags & ZDB_FLAG_PRINT_BLKPTR)
5780                 zdb_print_blkptr((blkptr_t *)(void *)
5781                     ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
5782         else if (flags & ZDB_FLAG_RAW)
5783                 zdb_dump_block_raw(buf, size, flags);
5784         else if (flags & ZDB_FLAG_INDIRECT)
5785                 zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
5786                     flags);
5787         else if (flags & ZDB_FLAG_GBH)
5788                 zdb_dump_gbh(buf, flags);
5789         else
5790                 zdb_dump_block(thing, buf, size, flags);
5791
5792         if (borrowed)
5793                 abd_return_buf_copy(pabd, buf, size);
5794
5795 out:
5796         abd_free(pabd);
5797         umem_free(lbuf, SPA_MAXBLOCKSIZE);
5798         free(dup);
5799 }
5800
5801 static void
5802 zdb_embedded_block(char *thing)
5803 {
5804         blkptr_t bp;
5805         unsigned long long *words = (void *)&bp;
5806         char *buf;
5807         int err;
5808
5809         bzero(&bp, sizeof (bp));
5810         err = sscanf(thing, "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx:"
5811             "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx",
5812             words + 0, words + 1, words + 2, words + 3,
5813             words + 4, words + 5, words + 6, words + 7,
5814             words + 8, words + 9, words + 10, words + 11,
5815             words + 12, words + 13, words + 14, words + 15);
5816         if (err != 16) {
5817                 (void) fprintf(stderr, "invalid input format\n");
5818                 exit(1);
5819         }
5820         ASSERT3U(BPE_GET_LSIZE(&bp), <=, SPA_MAXBLOCKSIZE);
5821         buf = malloc(SPA_MAXBLOCKSIZE);
5822         if (buf == NULL) {
5823                 (void) fprintf(stderr, "out of memory\n");
5824                 exit(1);
5825         }
5826         err = decode_embedded_bp(&bp, buf, BPE_GET_LSIZE(&bp));
5827         if (err != 0) {
5828                 (void) fprintf(stderr, "decode failed: %u\n", err);
5829                 exit(1);
5830         }
5831         zdb_dump_block_raw(buf, BPE_GET_LSIZE(&bp), 0);
5832         free(buf);
5833 }
5834
5835 int
5836 main(int argc, char **argv)
5837 {
5838         int c;
5839         struct rlimit rl = { 1024, 1024 };
5840         spa_t *spa = NULL;
5841         objset_t *os = NULL;
5842         int dump_all = 1;
5843         int verbose = 0;
5844         int error = 0;
5845         char **searchdirs = NULL;
5846         int nsearch = 0;
5847         char *target, *target_pool;
5848         nvlist_t *policy = NULL;
5849         uint64_t max_txg = UINT64_MAX;
5850         int flags = ZFS_IMPORT_MISSING_LOG;
5851         int rewind = ZPOOL_NEVER_REWIND;
5852         char *spa_config_path_env;
5853         boolean_t target_is_spa = B_TRUE;
5854         nvlist_t *cfg = NULL;
5855
5856         (void) setrlimit(RLIMIT_NOFILE, &rl);
5857         (void) enable_extended_FILE_stdio(-1, -1);
5858
5859         dprintf_setup(&argc, argv);
5860
5861         /*
5862          * If there is an environment variable SPA_CONFIG_PATH it overrides
5863          * default spa_config_path setting. If -U flag is specified it will
5864          * override this environment variable settings once again.
5865          */
5866         spa_config_path_env = getenv("SPA_CONFIG_PATH");
5867         if (spa_config_path_env != NULL)
5868                 spa_config_path = spa_config_path_env;
5869
5870         while ((c = getopt(argc, argv,
5871             "AbcCdDeEFGhiI:klLmMo:Op:PqRsSt:uU:vVx:X")) != -1) {
5872                 switch (c) {
5873                 case 'b':
5874                 case 'c':
5875                 case 'C':
5876                 case 'd':
5877                 case 'D':
5878                 case 'E':
5879                 case 'G':
5880                 case 'h':
5881                 case 'i':
5882                 case 'l':
5883                 case 'm':
5884                 case 'M':
5885                 case 'O':
5886                 case 'R':
5887                 case 's':
5888                 case 'S':
5889                 case 'u':
5890                         dump_opt[c]++;
5891                         dump_all = 0;
5892                         break;
5893                 case 'A':
5894                 case 'e':
5895                 case 'F':
5896                 case 'k':
5897                 case 'L':
5898                 case 'P':
5899                 case 'q':
5900                 case 'X':
5901                         dump_opt[c]++;
5902                         break;
5903                 /* NB: Sort single match options below. */
5904                 case 'I':
5905                         max_inflight = strtoull(optarg, NULL, 0);
5906                         if (max_inflight == 0) {
5907                                 (void) fprintf(stderr, "maximum number "
5908                                     "of inflight I/Os must be greater "
5909                                     "than 0\n");
5910                                 usage();
5911                         }
5912                         break;
5913                 case 'o':
5914                         error = set_global_var(optarg);
5915                         if (error != 0)
5916                                 usage();
5917                         break;
5918                 case 'p':
5919                         if (searchdirs == NULL) {
5920                                 searchdirs = umem_alloc(sizeof (char *),
5921                                     UMEM_NOFAIL);
5922                         } else {
5923                                 char **tmp = umem_alloc((nsearch + 1) *
5924                                     sizeof (char *), UMEM_NOFAIL);
5925                                 bcopy(searchdirs, tmp, nsearch *
5926                                     sizeof (char *));
5927                                 umem_free(searchdirs,
5928                                     nsearch * sizeof (char *));
5929                                 searchdirs = tmp;
5930                         }
5931                         searchdirs[nsearch++] = optarg;
5932                         break;
5933                 case 't':
5934                         max_txg = strtoull(optarg, NULL, 0);
5935                         if (max_txg < TXG_INITIAL) {
5936                                 (void) fprintf(stderr, "incorrect txg "
5937                                     "specified: %s\n", optarg);
5938                                 usage();
5939                         }
5940                         break;
5941                 case 'U':
5942                         spa_config_path = optarg;
5943                         if (spa_config_path[0] != '/') {
5944                                 (void) fprintf(stderr,
5945                                     "cachefile must be an absolute path "
5946                                     "(i.e. start with a slash)\n");
5947                                 usage();
5948                         }
5949                         break;
5950                 case 'v':
5951                         verbose++;
5952                         break;
5953                 case 'V':
5954                         flags = ZFS_IMPORT_VERBATIM;
5955                         break;
5956                 case 'x':
5957                         vn_dumpdir = optarg;
5958                         break;
5959                 default:
5960                         usage();
5961                         break;
5962                 }
5963         }
5964
5965         if (!dump_opt['e'] && searchdirs != NULL) {
5966                 (void) fprintf(stderr, "-p option requires use of -e\n");
5967                 usage();
5968         }
5969
5970 #if defined(_LP64)
5971         /*
5972          * ZDB does not typically re-read blocks; therefore limit the ARC
5973          * to 256 MB, which can be used entirely for metadata.
5974          */
5975         zfs_arc_max = zfs_arc_meta_limit = 256 * 1024 * 1024;
5976 #endif
5977
5978         /*
5979          * "zdb -c" uses checksum-verifying scrub i/os which are async reads.
5980          * "zdb -b" uses traversal prefetch which uses async reads.
5981          * For good performance, let several of them be active at once.
5982          */
5983         zfs_vdev_async_read_max_active = 10;
5984
5985         /*
5986          * Disable reference tracking for better performance.
5987          */
5988         reference_tracking_enable = B_FALSE;
5989
5990         /*
5991          * Do not fail spa_load when spa_load_verify fails. This is needed
5992          * to load non-idle pools.
5993          */
5994         spa_load_verify_dryrun = B_TRUE;
5995
5996         kernel_init(FREAD);
5997         if ((g_zfs = libzfs_init()) == NULL) {
5998                 (void) fprintf(stderr, "%s", libzfs_error_init(errno));
5999                 return (1);
6000         }
6001
6002         if (dump_all)
6003                 verbose = MAX(verbose, 1);
6004
6005         for (c = 0; c < 256; c++) {
6006                 if (dump_all && strchr("AeEFklLOPRSX", c) == NULL)
6007                         dump_opt[c] = 1;
6008                 if (dump_opt[c])
6009                         dump_opt[c] += verbose;
6010         }
6011
6012         aok = (dump_opt['A'] == 1) || (dump_opt['A'] > 2);
6013         zfs_recover = (dump_opt['A'] > 1);
6014
6015         argc -= optind;
6016         argv += optind;
6017
6018         if (argc < 2 && dump_opt['R'])
6019                 usage();
6020
6021         if (dump_opt['E']) {
6022                 if (argc != 1)
6023                         usage();
6024                 zdb_embedded_block(argv[0]);
6025                 return (0);
6026         }
6027
6028         if (argc < 1) {
6029                 if (!dump_opt['e'] && dump_opt['C']) {
6030                         dump_cachefile(spa_config_path);
6031                         return (0);
6032                 }
6033                 usage();
6034         }
6035
6036         if (dump_opt['l'])
6037                 return (dump_label(argv[0]));
6038
6039         if (dump_opt['O']) {
6040                 if (argc != 2)
6041                         usage();
6042                 dump_opt['v'] = verbose + 3;
6043                 return (dump_path(argv[0], argv[1]));
6044         }
6045
6046         if (dump_opt['X'] || dump_opt['F'])
6047                 rewind = ZPOOL_DO_REWIND |
6048                     (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
6049
6050         if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
6051             nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, max_txg) != 0 ||
6052             nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY, rewind) != 0)
6053                 fatal("internal error: %s", strerror(ENOMEM));
6054
6055         error = 0;
6056         target = argv[0];
6057
6058         char *checkpoint_pool = NULL;
6059         char *checkpoint_target = NULL;
6060         if (dump_opt['k']) {
6061                 checkpoint_pool = import_checkpointed_state(target, cfg,
6062                     &checkpoint_target);
6063
6064                 if (checkpoint_target != NULL)
6065                         target = checkpoint_target;
6066
6067         }
6068
6069         if (strpbrk(target, "/@") != NULL) {
6070                 size_t targetlen;
6071
6072                 target_pool = strdup(target);
6073                 *strpbrk(target_pool, "/@") = '\0';
6074
6075                 target_is_spa = B_FALSE;
6076                 targetlen = strlen(target);
6077                 if (targetlen && target[targetlen - 1] == '/')
6078                         target[targetlen - 1] = '\0';
6079         } else {
6080                 target_pool = target;
6081         }
6082
6083         if (dump_opt['e']) {
6084                 importargs_t args = { 0 };
6085
6086                 args.paths = nsearch;
6087                 args.path = searchdirs;
6088                 args.can_be_active = B_TRUE;
6089
6090                 error = zpool_tryimport(g_zfs, target_pool, &cfg, &args);
6091
6092                 if (error == 0) {
6093
6094                         if (nvlist_add_nvlist(cfg,
6095                             ZPOOL_LOAD_POLICY, policy) != 0) {
6096                                 fatal("can't open '%s': %s",
6097                                     target, strerror(ENOMEM));
6098                         }
6099
6100                         if (dump_opt['C'] > 1) {
6101                                 (void) printf("\nConfiguration for import:\n");
6102                                 dump_nvlist(cfg, 8);
6103                         }
6104
6105                         /*
6106                          * Disable the activity check to allow examination of
6107                          * active pools.
6108                          */
6109                         error = spa_import(target_pool, cfg, NULL,
6110                             flags | ZFS_IMPORT_SKIP_MMP);
6111                 }
6112         }
6113
6114         if (target_pool != target)
6115                 free(target_pool);
6116
6117         if (error == 0) {
6118                 if (dump_opt['k'] && (target_is_spa || dump_opt['R'])) {
6119                         ASSERT(checkpoint_pool != NULL);
6120                         ASSERT(checkpoint_target == NULL);
6121
6122                         error = spa_open(checkpoint_pool, &spa, FTAG);
6123                         if (error != 0) {
6124                                 fatal("Tried to open pool \"%s\" but "
6125                                     "spa_open() failed with error %d\n",
6126                                     checkpoint_pool, error);
6127                         }
6128
6129                 } else if (target_is_spa || dump_opt['R']) {
6130                         zdb_set_skip_mmp(target);
6131                         error = spa_open_rewind(target, &spa, FTAG, policy,
6132                             NULL);
6133                         if (error) {
6134                                 /*
6135                                  * If we're missing the log device then
6136                                  * try opening the pool after clearing the
6137                                  * log state.
6138                                  */
6139                                 mutex_enter(&spa_namespace_lock);
6140                                 if ((spa = spa_lookup(target)) != NULL &&
6141                                     spa->spa_log_state == SPA_LOG_MISSING) {
6142                                         spa->spa_log_state = SPA_LOG_CLEAR;
6143                                         error = 0;
6144                                 }
6145                                 mutex_exit(&spa_namespace_lock);
6146
6147                                 if (!error) {
6148                                         error = spa_open_rewind(target, &spa,
6149                                             FTAG, policy, NULL);
6150                                 }
6151                         }
6152                 } else {
6153                         zdb_set_skip_mmp(target);
6154                         error = open_objset(target, DMU_OST_ANY, FTAG, &os);
6155                         if (error == 0)
6156                                 spa = dmu_objset_spa(os);
6157                 }
6158         }
6159         nvlist_free(policy);
6160
6161         if (error)
6162                 fatal("can't open '%s': %s", target, strerror(error));
6163
6164         /*
6165          * Set the pool failure mode to panic in order to prevent the pool
6166          * from suspending.  A suspended I/O will have no way to resume and
6167          * can prevent the zdb(8) command from terminating as expected.
6168          */
6169         if (spa != NULL)
6170                 spa->spa_failmode = ZIO_FAILURE_MODE_PANIC;
6171
6172         argv++;
6173         argc--;
6174         if (!dump_opt['R']) {
6175                 if (argc > 0) {
6176                         zopt_objects = argc;
6177                         zopt_object = calloc(zopt_objects, sizeof (uint64_t));
6178                         for (unsigned i = 0; i < zopt_objects; i++) {
6179                                 errno = 0;
6180                                 zopt_object[i] = strtoull(argv[i], NULL, 0);
6181                                 if (zopt_object[i] == 0 && errno != 0)
6182                                         fatal("bad number %s: %s",
6183                                             argv[i], strerror(errno));
6184                         }
6185                 }
6186                 if (os != NULL) {
6187                         dump_dir(os);
6188                 } else if (zopt_objects > 0 && !dump_opt['m']) {
6189                         dump_dir(spa->spa_meta_objset);
6190                 } else {
6191                         dump_zpool(spa);
6192                 }
6193         } else {
6194                 flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
6195                 flagbits['c'] = ZDB_FLAG_CHECKSUM;
6196                 flagbits['d'] = ZDB_FLAG_DECOMPRESS;
6197                 flagbits['e'] = ZDB_FLAG_BSWAP;
6198                 flagbits['g'] = ZDB_FLAG_GBH;
6199                 flagbits['i'] = ZDB_FLAG_INDIRECT;
6200                 flagbits['p'] = ZDB_FLAG_PHYS;
6201                 flagbits['r'] = ZDB_FLAG_RAW;
6202
6203                 for (int i = 0; i < argc; i++)
6204                         zdb_read_block(argv[i], spa);
6205         }
6206
6207         if (dump_opt['k']) {
6208                 free(checkpoint_pool);
6209                 if (!target_is_spa)
6210                         free(checkpoint_target);
6211         }
6212
6213         if (os != NULL)
6214                 close_objset(os, FTAG);
6215         else
6216                 spa_close(spa, FTAG);
6217
6218         fuid_table_destroy();
6219
6220         dump_debug_buffer();
6221
6222         libzfs_fini(g_zfs);
6223         kernel_fini();
6224
6225         return (error);
6226 }