]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - cmd/zdb/zdb.c
Vendor import of openzfs master @ 184df27eef0abdc7ab2105b21257f753834b936b
[FreeBSD/FreeBSD.git] / 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, 2019 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  * Copyright (c) 2020 Datto Inc.
30  * Copyright (c) 2020, The FreeBSD Foundation [1]
31  *
32  * [1] Portions of this software were developed by Allan Jude
33  *     under sponsorship from the FreeBSD Foundation.
34  */
35
36 #include <stdio.h>
37 #include <unistd.h>
38 #include <stdlib.h>
39 #include <ctype.h>
40 #include <sys/zfs_context.h>
41 #include <sys/spa.h>
42 #include <sys/spa_impl.h>
43 #include <sys/dmu.h>
44 #include <sys/zap.h>
45 #include <sys/fs/zfs.h>
46 #include <sys/zfs_znode.h>
47 #include <sys/zfs_sa.h>
48 #include <sys/sa.h>
49 #include <sys/sa_impl.h>
50 #include <sys/vdev.h>
51 #include <sys/vdev_impl.h>
52 #include <sys/metaslab_impl.h>
53 #include <sys/dmu_objset.h>
54 #include <sys/dsl_dir.h>
55 #include <sys/dsl_dataset.h>
56 #include <sys/dsl_pool.h>
57 #include <sys/dsl_bookmark.h>
58 #include <sys/dbuf.h>
59 #include <sys/zil.h>
60 #include <sys/zil_impl.h>
61 #include <sys/stat.h>
62 #include <sys/resource.h>
63 #include <sys/dmu_send.h>
64 #include <sys/dmu_traverse.h>
65 #include <sys/zio_checksum.h>
66 #include <sys/zio_compress.h>
67 #include <sys/zfs_fuid.h>
68 #include <sys/arc.h>
69 #include <sys/arc_impl.h>
70 #include <sys/ddt.h>
71 #include <sys/zfeature.h>
72 #include <sys/abd.h>
73 #include <sys/blkptr.h>
74 #include <sys/dsl_crypt.h>
75 #include <sys/dsl_scan.h>
76 #include <sys/btree.h>
77 #include <zfs_comutil.h>
78 #include <sys/zstd/zstd.h>
79
80 #include <libnvpair.h>
81 #include <libzutil.h>
82
83 #include "zdb.h"
84
85 #define ZDB_COMPRESS_NAME(idx) ((idx) < ZIO_COMPRESS_FUNCTIONS ?        \
86         zio_compress_table[(idx)].ci_name : "UNKNOWN")
87 #define ZDB_CHECKSUM_NAME(idx) ((idx) < ZIO_CHECKSUM_FUNCTIONS ?        \
88         zio_checksum_table[(idx)].ci_name : "UNKNOWN")
89 #define ZDB_OT_TYPE(idx) ((idx) < DMU_OT_NUMTYPES ? (idx) :             \
90         (idx) == DMU_OTN_ZAP_DATA || (idx) == DMU_OTN_ZAP_METADATA ?    \
91         DMU_OT_ZAP_OTHER : \
92         (idx) == DMU_OTN_UINT64_DATA || (idx) == DMU_OTN_UINT64_METADATA ? \
93         DMU_OT_UINT64_OTHER : DMU_OT_NUMTYPES)
94
95 static char *
96 zdb_ot_name(dmu_object_type_t type)
97 {
98         if (type < DMU_OT_NUMTYPES)
99                 return (dmu_ot[type].ot_name);
100         else if ((type & DMU_OT_NEWTYPE) &&
101             ((type & DMU_OT_BYTESWAP_MASK) < DMU_BSWAP_NUMFUNCS))
102                 return (dmu_ot_byteswap[type & DMU_OT_BYTESWAP_MASK].ob_name);
103         else
104                 return ("UNKNOWN");
105 }
106
107 extern int reference_tracking_enable;
108 extern int zfs_recover;
109 extern unsigned long zfs_arc_meta_min, zfs_arc_meta_limit;
110 extern int zfs_vdev_async_read_max_active;
111 extern boolean_t spa_load_verify_dryrun;
112 extern int zfs_reconstruct_indirect_combinations_max;
113 extern int zfs_btree_verify_intensity;
114
115 static const char cmdname[] = "zdb";
116 uint8_t dump_opt[256];
117
118 typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
119
120 uint64_t *zopt_metaslab = NULL;
121 static unsigned zopt_metaslab_args = 0;
122
123 typedef struct zopt_object_range {
124         uint64_t zor_obj_start;
125         uint64_t zor_obj_end;
126         uint64_t zor_flags;
127 } zopt_object_range_t;
128 zopt_object_range_t *zopt_object_ranges = NULL;
129 static unsigned zopt_object_args = 0;
130
131 static int flagbits[256];
132
133 #define ZOR_FLAG_PLAIN_FILE     0x0001
134 #define ZOR_FLAG_DIRECTORY      0x0002
135 #define ZOR_FLAG_SPACE_MAP      0x0004
136 #define ZOR_FLAG_ZAP            0x0008
137 #define ZOR_FLAG_ALL_TYPES      -1
138 #define ZOR_SUPPORTED_FLAGS     (ZOR_FLAG_PLAIN_FILE    | \
139                                 ZOR_FLAG_DIRECTORY      | \
140                                 ZOR_FLAG_SPACE_MAP      | \
141                                 ZOR_FLAG_ZAP)
142
143 #define ZDB_FLAG_CHECKSUM       0x0001
144 #define ZDB_FLAG_DECOMPRESS     0x0002
145 #define ZDB_FLAG_BSWAP          0x0004
146 #define ZDB_FLAG_GBH            0x0008
147 #define ZDB_FLAG_INDIRECT       0x0010
148 #define ZDB_FLAG_RAW            0x0020
149 #define ZDB_FLAG_PRINT_BLKPTR   0x0040
150 #define ZDB_FLAG_VERBOSE        0x0080
151
152 uint64_t max_inflight_bytes = 256 * 1024 * 1024; /* 256MB */
153 static int leaked_objects = 0;
154 static range_tree_t *mos_refd_objs;
155
156 static void snprintf_blkptr_compact(char *, size_t, const blkptr_t *,
157     boolean_t);
158 static void mos_obj_refd(uint64_t);
159 static void mos_obj_refd_multiple(uint64_t);
160 static int dump_bpobj_cb(void *arg, const blkptr_t *bp, boolean_t free,
161     dmu_tx_t *tx);
162
163 typedef struct sublivelist_verify {
164         /* all ALLOC'd blkptr_t in one sub-livelist */
165         zfs_btree_t sv_all_allocs;
166
167         /* all FREE'd blkptr_t in one sub-livelist */
168         zfs_btree_t sv_all_frees;
169
170         /* FREE's that haven't yet matched to an ALLOC, in one sub-livelist */
171         zfs_btree_t sv_pair;
172
173         /* ALLOC's without a matching FREE, accumulates across sub-livelists */
174         zfs_btree_t sv_leftover;
175 } sublivelist_verify_t;
176
177 static int
178 livelist_compare(const void *larg, const void *rarg)
179 {
180         const blkptr_t *l = larg;
181         const blkptr_t *r = rarg;
182
183         /* Sort them according to dva[0] */
184         uint64_t l_dva0_vdev, r_dva0_vdev;
185         l_dva0_vdev = DVA_GET_VDEV(&l->blk_dva[0]);
186         r_dva0_vdev = DVA_GET_VDEV(&r->blk_dva[0]);
187         if (l_dva0_vdev < r_dva0_vdev)
188                 return (-1);
189         else if (l_dva0_vdev > r_dva0_vdev)
190                 return (+1);
191
192         /* if vdevs are equal, sort by offsets. */
193         uint64_t l_dva0_offset;
194         uint64_t r_dva0_offset;
195         l_dva0_offset = DVA_GET_OFFSET(&l->blk_dva[0]);
196         r_dva0_offset = DVA_GET_OFFSET(&r->blk_dva[0]);
197         if (l_dva0_offset < r_dva0_offset) {
198                 return (-1);
199         } else if (l_dva0_offset > r_dva0_offset) {
200                 return (+1);
201         }
202
203         /*
204          * Since we're storing blkptrs without cancelling FREE/ALLOC pairs,
205          * it's possible the offsets are equal. In that case, sort by txg
206          */
207         if (l->blk_birth < r->blk_birth) {
208                 return (-1);
209         } else if (l->blk_birth > r->blk_birth) {
210                 return (+1);
211         }
212         return (0);
213 }
214
215 typedef struct sublivelist_verify_block {
216         dva_t svb_dva;
217
218         /*
219          * We need this to check if the block marked as allocated
220          * in the livelist was freed (and potentially reallocated)
221          * in the metaslab spacemaps at a later TXG.
222          */
223         uint64_t svb_allocated_txg;
224 } sublivelist_verify_block_t;
225
226 static void zdb_print_blkptr(const blkptr_t *bp, int flags);
227
228 static int
229 sublivelist_verify_blkptr(void *arg, const blkptr_t *bp, boolean_t free,
230     dmu_tx_t *tx)
231 {
232         ASSERT3P(tx, ==, NULL);
233         struct sublivelist_verify *sv = arg;
234         char blkbuf[BP_SPRINTF_LEN];
235         zfs_btree_index_t where;
236         if (free) {
237                 zfs_btree_add(&sv->sv_pair, bp);
238                 /* Check if the FREE is a duplicate */
239                 if (zfs_btree_find(&sv->sv_all_frees, bp, &where) != NULL) {
240                         snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp,
241                             free);
242                         (void) printf("\tERROR: Duplicate FREE: %s\n", blkbuf);
243                 } else {
244                         zfs_btree_add_idx(&sv->sv_all_frees, bp, &where);
245                 }
246         } else {
247                 /* Check if the ALLOC has been freed */
248                 if (zfs_btree_find(&sv->sv_pair, bp, &where) != NULL) {
249                         zfs_btree_remove_idx(&sv->sv_pair, &where);
250                 } else {
251                         for (int i = 0; i < SPA_DVAS_PER_BP; i++) {
252                                 if (DVA_IS_EMPTY(&bp->blk_dva[i]))
253                                         break;
254                                 sublivelist_verify_block_t svb = {
255                                     .svb_dva = bp->blk_dva[i],
256                                     .svb_allocated_txg = bp->blk_birth
257                                 };
258
259                                 if (zfs_btree_find(&sv->sv_leftover, &svb,
260                                     &where) == NULL) {
261                                         zfs_btree_add_idx(&sv->sv_leftover,
262                                             &svb, &where);
263                                 }
264                         }
265                 }
266                 /* Check if the ALLOC is a duplicate */
267                 if (zfs_btree_find(&sv->sv_all_allocs, bp, &where) != NULL) {
268                         snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp,
269                             free);
270                         (void) printf("\tERROR: Duplicate ALLOC: %s\n", blkbuf);
271                 } else {
272                         zfs_btree_add_idx(&sv->sv_all_allocs, bp, &where);
273                 }
274         }
275         return (0);
276 }
277
278 static int
279 sublivelist_verify_func(void *args, dsl_deadlist_entry_t *dle)
280 {
281         int err;
282         char blkbuf[BP_SPRINTF_LEN];
283         struct sublivelist_verify *sv = args;
284
285         zfs_btree_create(&sv->sv_all_allocs, livelist_compare,
286             sizeof (blkptr_t));
287
288         zfs_btree_create(&sv->sv_all_frees, livelist_compare,
289             sizeof (blkptr_t));
290
291         zfs_btree_create(&sv->sv_pair, livelist_compare,
292             sizeof (blkptr_t));
293
294         err = bpobj_iterate_nofree(&dle->dle_bpobj, sublivelist_verify_blkptr,
295             sv, NULL);
296
297         zfs_btree_clear(&sv->sv_all_allocs);
298         zfs_btree_destroy(&sv->sv_all_allocs);
299
300         zfs_btree_clear(&sv->sv_all_frees);
301         zfs_btree_destroy(&sv->sv_all_frees);
302
303         blkptr_t *e;
304         zfs_btree_index_t *cookie = NULL;
305         while ((e = zfs_btree_destroy_nodes(&sv->sv_pair, &cookie)) != NULL) {
306                 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), e, B_TRUE);
307                 (void) printf("\tERROR: Unmatched FREE: %s\n", blkbuf);
308         }
309         zfs_btree_destroy(&sv->sv_pair);
310
311         return (err);
312 }
313
314 static int
315 livelist_block_compare(const void *larg, const void *rarg)
316 {
317         const sublivelist_verify_block_t *l = larg;
318         const sublivelist_verify_block_t *r = rarg;
319
320         if (DVA_GET_VDEV(&l->svb_dva) < DVA_GET_VDEV(&r->svb_dva))
321                 return (-1);
322         else if (DVA_GET_VDEV(&l->svb_dva) > DVA_GET_VDEV(&r->svb_dva))
323                 return (+1);
324
325         if (DVA_GET_OFFSET(&l->svb_dva) < DVA_GET_OFFSET(&r->svb_dva))
326                 return (-1);
327         else if (DVA_GET_OFFSET(&l->svb_dva) > DVA_GET_OFFSET(&r->svb_dva))
328                 return (+1);
329
330         if (DVA_GET_ASIZE(&l->svb_dva) < DVA_GET_ASIZE(&r->svb_dva))
331                 return (-1);
332         else if (DVA_GET_ASIZE(&l->svb_dva) > DVA_GET_ASIZE(&r->svb_dva))
333                 return (+1);
334
335         return (0);
336 }
337
338 /*
339  * Check for errors in a livelist while tracking all unfreed ALLOCs in the
340  * sublivelist_verify_t: sv->sv_leftover
341  */
342 static void
343 livelist_verify(dsl_deadlist_t *dl, void *arg)
344 {
345         sublivelist_verify_t *sv = arg;
346         dsl_deadlist_iterate(dl, sublivelist_verify_func, sv);
347 }
348
349 /*
350  * Check for errors in the livelist entry and discard the intermediary
351  * data structures
352  */
353 /* ARGSUSED */
354 static int
355 sublivelist_verify_lightweight(void *args, dsl_deadlist_entry_t *dle)
356 {
357         sublivelist_verify_t sv;
358         zfs_btree_create(&sv.sv_leftover, livelist_block_compare,
359             sizeof (sublivelist_verify_block_t));
360         int err = sublivelist_verify_func(&sv, dle);
361         zfs_btree_clear(&sv.sv_leftover);
362         zfs_btree_destroy(&sv.sv_leftover);
363         return (err);
364 }
365
366 typedef struct metaslab_verify {
367         /*
368          * Tree containing all the leftover ALLOCs from the livelists
369          * that are part of this metaslab.
370          */
371         zfs_btree_t mv_livelist_allocs;
372
373         /*
374          * Metaslab information.
375          */
376         uint64_t mv_vdid;
377         uint64_t mv_msid;
378         uint64_t mv_start;
379         uint64_t mv_end;
380
381         /*
382          * What's currently allocated for this metaslab.
383          */
384         range_tree_t *mv_allocated;
385 } metaslab_verify_t;
386
387 typedef void ll_iter_t(dsl_deadlist_t *ll, void *arg);
388
389 typedef int (*zdb_log_sm_cb_t)(spa_t *spa, space_map_entry_t *sme, uint64_t txg,
390     void *arg);
391
392 typedef struct unflushed_iter_cb_arg {
393         spa_t *uic_spa;
394         uint64_t uic_txg;
395         void *uic_arg;
396         zdb_log_sm_cb_t uic_cb;
397 } unflushed_iter_cb_arg_t;
398
399 static int
400 iterate_through_spacemap_logs_cb(space_map_entry_t *sme, void *arg)
401 {
402         unflushed_iter_cb_arg_t *uic = arg;
403         return (uic->uic_cb(uic->uic_spa, sme, uic->uic_txg, uic->uic_arg));
404 }
405
406 static void
407 iterate_through_spacemap_logs(spa_t *spa, zdb_log_sm_cb_t cb, void *arg)
408 {
409         if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
410                 return;
411
412         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
413         for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
414             sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls)) {
415                 space_map_t *sm = NULL;
416                 VERIFY0(space_map_open(&sm, spa_meta_objset(spa),
417                     sls->sls_sm_obj, 0, UINT64_MAX, SPA_MINBLOCKSHIFT));
418
419                 unflushed_iter_cb_arg_t uic = {
420                         .uic_spa = spa,
421                         .uic_txg = sls->sls_txg,
422                         .uic_arg = arg,
423                         .uic_cb = cb
424                 };
425                 VERIFY0(space_map_iterate(sm, space_map_length(sm),
426                     iterate_through_spacemap_logs_cb, &uic));
427                 space_map_close(sm);
428         }
429         spa_config_exit(spa, SCL_CONFIG, FTAG);
430 }
431
432 static void
433 verify_livelist_allocs(metaslab_verify_t *mv, uint64_t txg,
434     uint64_t offset, uint64_t size)
435 {
436         sublivelist_verify_block_t svb;
437         DVA_SET_VDEV(&svb.svb_dva, mv->mv_vdid);
438         DVA_SET_OFFSET(&svb.svb_dva, offset);
439         DVA_SET_ASIZE(&svb.svb_dva, size);
440         zfs_btree_index_t where;
441         uint64_t end_offset = offset + size;
442
443         /*
444          *  Look for an exact match for spacemap entry in the livelist entries.
445          *  Then, look for other livelist entries that fall within the range
446          *  of the spacemap entry as it may have been condensed
447          */
448         sublivelist_verify_block_t *found =
449             zfs_btree_find(&mv->mv_livelist_allocs, &svb, &where);
450         if (found == NULL) {
451                 found = zfs_btree_next(&mv->mv_livelist_allocs, &where, &where);
452         }
453         for (; found != NULL && DVA_GET_VDEV(&found->svb_dva) == mv->mv_vdid &&
454             DVA_GET_OFFSET(&found->svb_dva) < end_offset;
455             found = zfs_btree_next(&mv->mv_livelist_allocs, &where, &where)) {
456                 if (found->svb_allocated_txg <= txg) {
457                         (void) printf("ERROR: Livelist ALLOC [%llx:%llx] "
458                             "from TXG %llx FREED at TXG %llx\n",
459                             (u_longlong_t)DVA_GET_OFFSET(&found->svb_dva),
460                             (u_longlong_t)DVA_GET_ASIZE(&found->svb_dva),
461                             (u_longlong_t)found->svb_allocated_txg,
462                             (u_longlong_t)txg);
463                 }
464         }
465 }
466
467 static int
468 metaslab_spacemap_validation_cb(space_map_entry_t *sme, void *arg)
469 {
470         metaslab_verify_t *mv = arg;
471         uint64_t offset = sme->sme_offset;
472         uint64_t size = sme->sme_run;
473         uint64_t txg = sme->sme_txg;
474
475         if (sme->sme_type == SM_ALLOC) {
476                 if (range_tree_contains(mv->mv_allocated,
477                     offset, size)) {
478                         (void) printf("ERROR: DOUBLE ALLOC: "
479                             "%llu [%llx:%llx] "
480                             "%llu:%llu LOG_SM\n",
481                             (u_longlong_t)txg, (u_longlong_t)offset,
482                             (u_longlong_t)size, (u_longlong_t)mv->mv_vdid,
483                             (u_longlong_t)mv->mv_msid);
484                 } else {
485                         range_tree_add(mv->mv_allocated,
486                             offset, size);
487                 }
488         } else {
489                 if (!range_tree_contains(mv->mv_allocated,
490                     offset, size)) {
491                         (void) printf("ERROR: DOUBLE FREE: "
492                             "%llu [%llx:%llx] "
493                             "%llu:%llu LOG_SM\n",
494                             (u_longlong_t)txg, (u_longlong_t)offset,
495                             (u_longlong_t)size, (u_longlong_t)mv->mv_vdid,
496                             (u_longlong_t)mv->mv_msid);
497                 } else {
498                         range_tree_remove(mv->mv_allocated,
499                             offset, size);
500                 }
501         }
502
503         if (sme->sme_type != SM_ALLOC) {
504                 /*
505                  * If something is freed in the spacemap, verify that
506                  * it is not listed as allocated in the livelist.
507                  */
508                 verify_livelist_allocs(mv, txg, offset, size);
509         }
510         return (0);
511 }
512
513 static int
514 spacemap_check_sm_log_cb(spa_t *spa, space_map_entry_t *sme,
515     uint64_t txg, void *arg)
516 {
517         metaslab_verify_t *mv = arg;
518         uint64_t offset = sme->sme_offset;
519         uint64_t vdev_id = sme->sme_vdev;
520
521         vdev_t *vd = vdev_lookup_top(spa, vdev_id);
522
523         /* skip indirect vdevs */
524         if (!vdev_is_concrete(vd))
525                 return (0);
526
527         if (vdev_id != mv->mv_vdid)
528                 return (0);
529
530         metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
531         if (ms->ms_id != mv->mv_msid)
532                 return (0);
533
534         if (txg < metaslab_unflushed_txg(ms))
535                 return (0);
536
537
538         ASSERT3U(txg, ==, sme->sme_txg);
539         return (metaslab_spacemap_validation_cb(sme, mv));
540 }
541
542 static void
543 spacemap_check_sm_log(spa_t *spa, metaslab_verify_t *mv)
544 {
545         iterate_through_spacemap_logs(spa, spacemap_check_sm_log_cb, mv);
546 }
547
548 static void
549 spacemap_check_ms_sm(space_map_t  *sm, metaslab_verify_t *mv)
550 {
551         if (sm == NULL)
552                 return;
553
554         VERIFY0(space_map_iterate(sm, space_map_length(sm),
555             metaslab_spacemap_validation_cb, mv));
556 }
557
558 static void iterate_deleted_livelists(spa_t *spa, ll_iter_t func, void *arg);
559
560 /*
561  * Transfer blocks from sv_leftover tree to the mv_livelist_allocs if
562  * they are part of that metaslab (mv_msid).
563  */
564 static void
565 mv_populate_livelist_allocs(metaslab_verify_t *mv, sublivelist_verify_t *sv)
566 {
567         zfs_btree_index_t where;
568         sublivelist_verify_block_t *svb;
569         ASSERT3U(zfs_btree_numnodes(&mv->mv_livelist_allocs), ==, 0);
570         for (svb = zfs_btree_first(&sv->sv_leftover, &where);
571             svb != NULL;
572             svb = zfs_btree_next(&sv->sv_leftover, &where, &where)) {
573                 if (DVA_GET_VDEV(&svb->svb_dva) != mv->mv_vdid)
574                         continue;
575
576                 if (DVA_GET_OFFSET(&svb->svb_dva) < mv->mv_start &&
577                     (DVA_GET_OFFSET(&svb->svb_dva) +
578                     DVA_GET_ASIZE(&svb->svb_dva)) > mv->mv_start) {
579                         (void) printf("ERROR: Found block that crosses "
580                             "metaslab boundary: <%llu:%llx:%llx>\n",
581                             (u_longlong_t)DVA_GET_VDEV(&svb->svb_dva),
582                             (u_longlong_t)DVA_GET_OFFSET(&svb->svb_dva),
583                             (u_longlong_t)DVA_GET_ASIZE(&svb->svb_dva));
584                         continue;
585                 }
586
587                 if (DVA_GET_OFFSET(&svb->svb_dva) < mv->mv_start)
588                         continue;
589
590                 if (DVA_GET_OFFSET(&svb->svb_dva) >= mv->mv_end)
591                         continue;
592
593                 if ((DVA_GET_OFFSET(&svb->svb_dva) +
594                     DVA_GET_ASIZE(&svb->svb_dva)) > mv->mv_end) {
595                         (void) printf("ERROR: Found block that crosses "
596                             "metaslab boundary: <%llu:%llx:%llx>\n",
597                             (u_longlong_t)DVA_GET_VDEV(&svb->svb_dva),
598                             (u_longlong_t)DVA_GET_OFFSET(&svb->svb_dva),
599                             (u_longlong_t)DVA_GET_ASIZE(&svb->svb_dva));
600                         continue;
601                 }
602
603                 zfs_btree_add(&mv->mv_livelist_allocs, svb);
604         }
605
606         for (svb = zfs_btree_first(&mv->mv_livelist_allocs, &where);
607             svb != NULL;
608             svb = zfs_btree_next(&mv->mv_livelist_allocs, &where, &where)) {
609                 zfs_btree_remove(&sv->sv_leftover, svb);
610         }
611 }
612
613 /*
614  * [Livelist Check]
615  * Iterate through all the sublivelists and:
616  * - report leftover frees
617  * - report double ALLOCs/FREEs
618  * - record leftover ALLOCs together with their TXG [see Cross Check]
619  *
620  * [Spacemap Check]
621  * for each metaslab:
622  * - iterate over spacemap and then the metaslab's entries in the
623  *   spacemap log, then report any double FREEs and ALLOCs (do not
624  *   blow up).
625  *
626  * [Cross Check]
627  * After finishing the Livelist Check phase and while being in the
628  * Spacemap Check phase, we find all the recorded leftover ALLOCs
629  * of the livelist check that are part of the metaslab that we are
630  * currently looking at in the Spacemap Check. We report any entries
631  * that are marked as ALLOCs in the livelists but have been actually
632  * freed (and potentially allocated again) after their TXG stamp in
633  * the spacemaps. Also report any ALLOCs from the livelists that
634  * belong to indirect vdevs (e.g. their vdev completed removal).
635  *
636  * Note that this will miss Log Spacemap entries that cancelled each other
637  * out before being flushed to the metaslab, so we are not guaranteed
638  * to match all erroneous ALLOCs.
639  */
640 static void
641 livelist_metaslab_validate(spa_t *spa)
642 {
643         (void) printf("Verifying deleted livelist entries\n");
644
645         sublivelist_verify_t sv;
646         zfs_btree_create(&sv.sv_leftover, livelist_block_compare,
647             sizeof (sublivelist_verify_block_t));
648         iterate_deleted_livelists(spa, livelist_verify, &sv);
649
650         (void) printf("Verifying metaslab entries\n");
651         vdev_t *rvd = spa->spa_root_vdev;
652         for (uint64_t c = 0; c < rvd->vdev_children; c++) {
653                 vdev_t *vd = rvd->vdev_child[c];
654
655                 if (!vdev_is_concrete(vd))
656                         continue;
657
658                 for (uint64_t mid = 0; mid < vd->vdev_ms_count; mid++) {
659                         metaslab_t *m = vd->vdev_ms[mid];
660
661                         (void) fprintf(stderr,
662                             "\rverifying concrete vdev %llu, "
663                             "metaslab %llu of %llu ...",
664                             (longlong_t)vd->vdev_id,
665                             (longlong_t)mid,
666                             (longlong_t)vd->vdev_ms_count);
667
668                         uint64_t shift, start;
669                         range_seg_type_t type =
670                             metaslab_calculate_range_tree_type(vd, m,
671                             &start, &shift);
672                         metaslab_verify_t mv;
673                         mv.mv_allocated = range_tree_create(NULL,
674                             type, NULL, start, shift);
675                         mv.mv_vdid = vd->vdev_id;
676                         mv.mv_msid = m->ms_id;
677                         mv.mv_start = m->ms_start;
678                         mv.mv_end = m->ms_start + m->ms_size;
679                         zfs_btree_create(&mv.mv_livelist_allocs,
680                             livelist_block_compare,
681                             sizeof (sublivelist_verify_block_t));
682
683                         mv_populate_livelist_allocs(&mv, &sv);
684
685                         spacemap_check_ms_sm(m->ms_sm, &mv);
686                         spacemap_check_sm_log(spa, &mv);
687
688                         range_tree_vacate(mv.mv_allocated, NULL, NULL);
689                         range_tree_destroy(mv.mv_allocated);
690                         zfs_btree_clear(&mv.mv_livelist_allocs);
691                         zfs_btree_destroy(&mv.mv_livelist_allocs);
692                 }
693         }
694         (void) fprintf(stderr, "\n");
695
696         /*
697          * If there are any segments in the leftover tree after we walked
698          * through all the metaslabs in the concrete vdevs then this means
699          * that we have segments in the livelists that belong to indirect
700          * vdevs and are marked as allocated.
701          */
702         if (zfs_btree_numnodes(&sv.sv_leftover) == 0) {
703                 zfs_btree_destroy(&sv.sv_leftover);
704                 return;
705         }
706         (void) printf("ERROR: Found livelist blocks marked as allocated "
707             "for indirect vdevs:\n");
708
709         zfs_btree_index_t *where = NULL;
710         sublivelist_verify_block_t *svb;
711         while ((svb = zfs_btree_destroy_nodes(&sv.sv_leftover, &where)) !=
712             NULL) {
713                 int vdev_id = DVA_GET_VDEV(&svb->svb_dva);
714                 ASSERT3U(vdev_id, <, rvd->vdev_children);
715                 vdev_t *vd = rvd->vdev_child[vdev_id];
716                 ASSERT(!vdev_is_concrete(vd));
717                 (void) printf("<%d:%llx:%llx> TXG %llx\n",
718                     vdev_id, (u_longlong_t)DVA_GET_OFFSET(&svb->svb_dva),
719                     (u_longlong_t)DVA_GET_ASIZE(&svb->svb_dva),
720                     (u_longlong_t)svb->svb_allocated_txg);
721         }
722         (void) printf("\n");
723         zfs_btree_destroy(&sv.sv_leftover);
724 }
725
726 /*
727  * These libumem hooks provide a reasonable set of defaults for the allocator's
728  * debugging facilities.
729  */
730 const char *
731 _umem_debug_init(void)
732 {
733         return ("default,verbose"); /* $UMEM_DEBUG setting */
734 }
735
736 const char *
737 _umem_logging_init(void)
738 {
739         return ("fail,contents"); /* $UMEM_LOGGING setting */
740 }
741
742 static void
743 usage(void)
744 {
745         (void) fprintf(stderr,
746             "Usage:\t%s [-AbcdDFGhikLMPsvXy] [-e [-V] [-p <path> ...]] "
747             "[-I <inflight I/Os>]\n"
748             "\t\t[-o <var>=<value>]... [-t <txg>] [-U <cache>] [-x <dumpdir>]\n"
749             "\t\t[<poolname>[/<dataset | objset id>] [<object | range> ...]]\n"
750             "\t%s [-AdiPv] [-e [-V] [-p <path> ...]] [-U <cache>]\n"
751             "\t\t[<poolname>[/<dataset | objset id>] [<object | range> ...]\n"
752             "\t%s [-v] <bookmark>\n"
753             "\t%s -C [-A] [-U <cache>]\n"
754             "\t%s -l [-Aqu] <device>\n"
755             "\t%s -m [-AFLPX] [-e [-V] [-p <path> ...]] [-t <txg>] "
756             "[-U <cache>]\n\t\t<poolname> [<vdev> [<metaslab> ...]]\n"
757             "\t%s -O <dataset> <path>\n"
758             "\t%s -R [-A] [-e [-V] [-p <path> ...]] [-U <cache>]\n"
759             "\t\t<poolname> <vdev>:<offset>:<size>[:<flags>]\n"
760             "\t%s -E [-A] word0:word1:...:word15\n"
761             "\t%s -S [-AP] [-e [-V] [-p <path> ...]] [-U <cache>] "
762             "<poolname>\n\n",
763             cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname,
764             cmdname, cmdname, cmdname);
765
766         (void) fprintf(stderr, "    Dataset name must include at least one "
767             "separator character '/' or '@'\n");
768         (void) fprintf(stderr, "    If dataset name is specified, only that "
769             "dataset is dumped\n");
770         (void) fprintf(stderr,  "    If object numbers or object number "
771             "ranges are specified, only those\n"
772             "    objects or ranges are dumped.\n\n");
773         (void) fprintf(stderr,
774             "    Object ranges take the form <start>:<end>[:<flags>]\n"
775             "        start    Starting object number\n"
776             "        end      Ending object number, or -1 for no upper bound\n"
777             "        flags    Optional flags to select object types:\n"
778             "            A     All objects (this is the default)\n"
779             "            d     ZFS directories\n"
780             "            f     ZFS files \n"
781             "            m     SPA space maps\n"
782             "            z     ZAPs\n"
783             "            -     Negate effect of next flag\n\n");
784         (void) fprintf(stderr, "    Options to control amount of output:\n");
785         (void) fprintf(stderr, "        -b block statistics\n");
786         (void) fprintf(stderr, "        -c checksum all metadata (twice for "
787             "all data) blocks\n");
788         (void) fprintf(stderr, "        -C config (or cachefile if alone)\n");
789         (void) fprintf(stderr, "        -d dataset(s)\n");
790         (void) fprintf(stderr, "        -D dedup statistics\n");
791         (void) fprintf(stderr, "        -E decode and display block from an "
792             "embedded block pointer\n");
793         (void) fprintf(stderr, "        -h pool history\n");
794         (void) fprintf(stderr, "        -i intent logs\n");
795         (void) fprintf(stderr, "        -l read label contents\n");
796         (void) fprintf(stderr, "        -k examine the checkpointed state "
797             "of the pool\n");
798         (void) fprintf(stderr, "        -L disable leak tracking (do not "
799             "load spacemaps)\n");
800         (void) fprintf(stderr, "        -m metaslabs\n");
801         (void) fprintf(stderr, "        -M metaslab groups\n");
802         (void) fprintf(stderr, "        -O perform object lookups by path\n");
803         (void) fprintf(stderr, "        -R read and display block from a "
804             "device\n");
805         (void) fprintf(stderr, "        -s report stats on zdb's I/O\n");
806         (void) fprintf(stderr, "        -S simulate dedup to measure effect\n");
807         (void) fprintf(stderr, "        -v verbose (applies to all "
808             "others)\n");
809         (void) fprintf(stderr, "        -y perform livelist and metaslab "
810             "validation on any livelists being deleted\n\n");
811         (void) fprintf(stderr, "    Below options are intended for use "
812             "with other options:\n");
813         (void) fprintf(stderr, "        -A ignore assertions (-A), enable "
814             "panic recovery (-AA) or both (-AAA)\n");
815         (void) fprintf(stderr, "        -e pool is exported/destroyed/"
816             "has altroot/not in a cachefile\n");
817         (void) fprintf(stderr, "        -F attempt automatic rewind within "
818             "safe range of transaction groups\n");
819         (void) fprintf(stderr, "        -G dump zfs_dbgmsg buffer before "
820             "exiting\n");
821         (void) fprintf(stderr, "        -I <number of inflight I/Os> -- "
822             "specify the maximum number of\n           "
823             "checksumming I/Os [default is 200]\n");
824         (void) fprintf(stderr, "        -o <variable>=<value> set global "
825             "variable to an unsigned 32-bit integer\n");
826         (void) fprintf(stderr, "        -p <path> -- use one or more with "
827             "-e to specify path to vdev dir\n");
828         (void) fprintf(stderr, "        -P print numbers in parseable form\n");
829         (void) fprintf(stderr, "        -q don't print label contents\n");
830         (void) fprintf(stderr, "        -t <txg> -- highest txg to use when "
831             "searching for uberblocks\n");
832         (void) fprintf(stderr, "        -u uberblock\n");
833         (void) fprintf(stderr, "        -U <cachefile_path> -- use alternate "
834             "cachefile\n");
835         (void) fprintf(stderr, "        -V do verbatim import\n");
836         (void) fprintf(stderr, "        -x <dumpdir> -- "
837             "dump all read blocks into specified directory\n");
838         (void) fprintf(stderr, "        -X attempt extreme rewind (does not "
839             "work with dataset)\n");
840         (void) fprintf(stderr, "        -Y attempt all reconstruction "
841             "combinations for split blocks\n");
842         (void) fprintf(stderr, "        -Z show ZSTD headers \n");
843         (void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
844             "to make only that option verbose\n");
845         (void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
846         exit(1);
847 }
848
849 static void
850 dump_debug_buffer(void)
851 {
852         if (dump_opt['G']) {
853                 (void) printf("\n");
854                 (void) fflush(stdout);
855                 zfs_dbgmsg_print("zdb");
856         }
857 }
858
859 /*
860  * Called for usage errors that are discovered after a call to spa_open(),
861  * dmu_bonus_hold(), or pool_match().  abort() is called for other errors.
862  */
863
864 static void
865 fatal(const char *fmt, ...)
866 {
867         va_list ap;
868
869         va_start(ap, fmt);
870         (void) fprintf(stderr, "%s: ", cmdname);
871         (void) vfprintf(stderr, fmt, ap);
872         va_end(ap);
873         (void) fprintf(stderr, "\n");
874
875         dump_debug_buffer();
876
877         exit(1);
878 }
879
880 /* ARGSUSED */
881 static void
882 dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
883 {
884         nvlist_t *nv;
885         size_t nvsize = *(uint64_t *)data;
886         char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
887
888         VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
889
890         VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
891
892         umem_free(packed, nvsize);
893
894         dump_nvlist(nv, 8);
895
896         nvlist_free(nv);
897 }
898
899 /* ARGSUSED */
900 static void
901 dump_history_offsets(objset_t *os, uint64_t object, void *data, size_t size)
902 {
903         spa_history_phys_t *shp = data;
904
905         if (shp == NULL)
906                 return;
907
908         (void) printf("\t\tpool_create_len = %llu\n",
909             (u_longlong_t)shp->sh_pool_create_len);
910         (void) printf("\t\tphys_max_off = %llu\n",
911             (u_longlong_t)shp->sh_phys_max_off);
912         (void) printf("\t\tbof = %llu\n",
913             (u_longlong_t)shp->sh_bof);
914         (void) printf("\t\teof = %llu\n",
915             (u_longlong_t)shp->sh_eof);
916         (void) printf("\t\trecords_lost = %llu\n",
917             (u_longlong_t)shp->sh_records_lost);
918 }
919
920 static void
921 zdb_nicenum(uint64_t num, char *buf, size_t buflen)
922 {
923         if (dump_opt['P'])
924                 (void) snprintf(buf, buflen, "%llu", (longlong_t)num);
925         else
926                 nicenum(num, buf, sizeof (buf));
927 }
928
929 static const char histo_stars[] = "****************************************";
930 static const uint64_t histo_width = sizeof (histo_stars) - 1;
931
932 static void
933 dump_histogram(const uint64_t *histo, int size, int offset)
934 {
935         int i;
936         int minidx = size - 1;
937         int maxidx = 0;
938         uint64_t max = 0;
939
940         for (i = 0; i < size; i++) {
941                 if (histo[i] > max)
942                         max = histo[i];
943                 if (histo[i] > 0 && i > maxidx)
944                         maxidx = i;
945                 if (histo[i] > 0 && i < minidx)
946                         minidx = i;
947         }
948
949         if (max < histo_width)
950                 max = histo_width;
951
952         for (i = minidx; i <= maxidx; i++) {
953                 (void) printf("\t\t\t%3u: %6llu %s\n",
954                     i + offset, (u_longlong_t)histo[i],
955                     &histo_stars[(max - histo[i]) * histo_width / max]);
956         }
957 }
958
959 static void
960 dump_zap_stats(objset_t *os, uint64_t object)
961 {
962         int error;
963         zap_stats_t zs;
964
965         error = zap_get_stats(os, object, &zs);
966         if (error)
967                 return;
968
969         if (zs.zs_ptrtbl_len == 0) {
970                 ASSERT(zs.zs_num_blocks == 1);
971                 (void) printf("\tmicrozap: %llu bytes, %llu entries\n",
972                     (u_longlong_t)zs.zs_blocksize,
973                     (u_longlong_t)zs.zs_num_entries);
974                 return;
975         }
976
977         (void) printf("\tFat ZAP stats:\n");
978
979         (void) printf("\t\tPointer table:\n");
980         (void) printf("\t\t\t%llu elements\n",
981             (u_longlong_t)zs.zs_ptrtbl_len);
982         (void) printf("\t\t\tzt_blk: %llu\n",
983             (u_longlong_t)zs.zs_ptrtbl_zt_blk);
984         (void) printf("\t\t\tzt_numblks: %llu\n",
985             (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
986         (void) printf("\t\t\tzt_shift: %llu\n",
987             (u_longlong_t)zs.zs_ptrtbl_zt_shift);
988         (void) printf("\t\t\tzt_blks_copied: %llu\n",
989             (u_longlong_t)zs.zs_ptrtbl_blks_copied);
990         (void) printf("\t\t\tzt_nextblk: %llu\n",
991             (u_longlong_t)zs.zs_ptrtbl_nextblk);
992
993         (void) printf("\t\tZAP entries: %llu\n",
994             (u_longlong_t)zs.zs_num_entries);
995         (void) printf("\t\tLeaf blocks: %llu\n",
996             (u_longlong_t)zs.zs_num_leafs);
997         (void) printf("\t\tTotal blocks: %llu\n",
998             (u_longlong_t)zs.zs_num_blocks);
999         (void) printf("\t\tzap_block_type: 0x%llx\n",
1000             (u_longlong_t)zs.zs_block_type);
1001         (void) printf("\t\tzap_magic: 0x%llx\n",
1002             (u_longlong_t)zs.zs_magic);
1003         (void) printf("\t\tzap_salt: 0x%llx\n",
1004             (u_longlong_t)zs.zs_salt);
1005
1006         (void) printf("\t\tLeafs with 2^n pointers:\n");
1007         dump_histogram(zs.zs_leafs_with_2n_pointers, ZAP_HISTOGRAM_SIZE, 0);
1008
1009         (void) printf("\t\tBlocks with n*5 entries:\n");
1010         dump_histogram(zs.zs_blocks_with_n5_entries, ZAP_HISTOGRAM_SIZE, 0);
1011
1012         (void) printf("\t\tBlocks n/10 full:\n");
1013         dump_histogram(zs.zs_blocks_n_tenths_full, ZAP_HISTOGRAM_SIZE, 0);
1014
1015         (void) printf("\t\tEntries with n chunks:\n");
1016         dump_histogram(zs.zs_entries_using_n_chunks, ZAP_HISTOGRAM_SIZE, 0);
1017
1018         (void) printf("\t\tBuckets with n entries:\n");
1019         dump_histogram(zs.zs_buckets_with_n_entries, ZAP_HISTOGRAM_SIZE, 0);
1020 }
1021
1022 /*ARGSUSED*/
1023 static void
1024 dump_none(objset_t *os, uint64_t object, void *data, size_t size)
1025 {
1026 }
1027
1028 /*ARGSUSED*/
1029 static void
1030 dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
1031 {
1032         (void) printf("\tUNKNOWN OBJECT TYPE\n");
1033 }
1034
1035 /*ARGSUSED*/
1036 static void
1037 dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
1038 {
1039 }
1040
1041 /*ARGSUSED*/
1042 static void
1043 dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
1044 {
1045         uint64_t *arr;
1046         uint64_t oursize;
1047         if (dump_opt['d'] < 6)
1048                 return;
1049
1050         if (data == NULL) {
1051                 dmu_object_info_t doi;
1052
1053                 VERIFY0(dmu_object_info(os, object, &doi));
1054                 size = doi.doi_max_offset;
1055                 /*
1056                  * We cap the size at 1 mebibyte here to prevent
1057                  * allocation failures and nigh-infinite printing if the
1058                  * object is extremely large.
1059                  */
1060                 oursize = MIN(size, 1 << 20);
1061                 arr = kmem_alloc(oursize, KM_SLEEP);
1062
1063                 int err = dmu_read(os, object, 0, oursize, arr, 0);
1064                 if (err != 0) {
1065                         (void) printf("got error %u from dmu_read\n", err);
1066                         kmem_free(arr, oursize);
1067                         return;
1068                 }
1069         } else {
1070                 /*
1071                  * Even though the allocation is already done in this code path,
1072                  * we still cap the size to prevent excessive printing.
1073                  */
1074                 oursize = MIN(size, 1 << 20);
1075                 arr = data;
1076         }
1077
1078         if (size == 0) {
1079                 (void) printf("\t\t[]\n");
1080                 return;
1081         }
1082
1083         (void) printf("\t\t[%0llx", (u_longlong_t)arr[0]);
1084         for (size_t i = 1; i * sizeof (uint64_t) < oursize; i++) {
1085                 if (i % 4 != 0)
1086                         (void) printf(", %0llx", (u_longlong_t)arr[i]);
1087                 else
1088                         (void) printf(",\n\t\t%0llx", (u_longlong_t)arr[i]);
1089         }
1090         if (oursize != size)
1091                 (void) printf(", ... ");
1092         (void) printf("]\n");
1093
1094         if (data == NULL)
1095                 kmem_free(arr, oursize);
1096 }
1097
1098 /*ARGSUSED*/
1099 static void
1100 dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
1101 {
1102         zap_cursor_t zc;
1103         zap_attribute_t attr;
1104         void *prop;
1105         unsigned i;
1106
1107         dump_zap_stats(os, object);
1108         (void) printf("\n");
1109
1110         for (zap_cursor_init(&zc, os, object);
1111             zap_cursor_retrieve(&zc, &attr) == 0;
1112             zap_cursor_advance(&zc)) {
1113                 (void) printf("\t\t%s = ", attr.za_name);
1114                 if (attr.za_num_integers == 0) {
1115                         (void) printf("\n");
1116                         continue;
1117                 }
1118                 prop = umem_zalloc(attr.za_num_integers *
1119                     attr.za_integer_length, UMEM_NOFAIL);
1120                 (void) zap_lookup(os, object, attr.za_name,
1121                     attr.za_integer_length, attr.za_num_integers, prop);
1122                 if (attr.za_integer_length == 1) {
1123                         (void) printf("%s", (char *)prop);
1124                 } else {
1125                         for (i = 0; i < attr.za_num_integers; i++) {
1126                                 switch (attr.za_integer_length) {
1127                                 case 2:
1128                                         (void) printf("%u ",
1129                                             ((uint16_t *)prop)[i]);
1130                                         break;
1131                                 case 4:
1132                                         (void) printf("%u ",
1133                                             ((uint32_t *)prop)[i]);
1134                                         break;
1135                                 case 8:
1136                                         (void) printf("%lld ",
1137                                             (u_longlong_t)((int64_t *)prop)[i]);
1138                                         break;
1139                                 }
1140                         }
1141                 }
1142                 (void) printf("\n");
1143                 umem_free(prop, attr.za_num_integers * attr.za_integer_length);
1144         }
1145         zap_cursor_fini(&zc);
1146 }
1147
1148 static void
1149 dump_bpobj(objset_t *os, uint64_t object, void *data, size_t size)
1150 {
1151         bpobj_phys_t *bpop = data;
1152         uint64_t i;
1153         char bytes[32], comp[32], uncomp[32];
1154
1155         /* make sure the output won't get truncated */
1156         CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1157         CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1158         CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1159
1160         if (bpop == NULL)
1161                 return;
1162
1163         zdb_nicenum(bpop->bpo_bytes, bytes, sizeof (bytes));
1164         zdb_nicenum(bpop->bpo_comp, comp, sizeof (comp));
1165         zdb_nicenum(bpop->bpo_uncomp, uncomp, sizeof (uncomp));
1166
1167         (void) printf("\t\tnum_blkptrs = %llu\n",
1168             (u_longlong_t)bpop->bpo_num_blkptrs);
1169         (void) printf("\t\tbytes = %s\n", bytes);
1170         if (size >= BPOBJ_SIZE_V1) {
1171                 (void) printf("\t\tcomp = %s\n", comp);
1172                 (void) printf("\t\tuncomp = %s\n", uncomp);
1173         }
1174         if (size >= BPOBJ_SIZE_V2) {
1175                 (void) printf("\t\tsubobjs = %llu\n",
1176                     (u_longlong_t)bpop->bpo_subobjs);
1177                 (void) printf("\t\tnum_subobjs = %llu\n",
1178                     (u_longlong_t)bpop->bpo_num_subobjs);
1179         }
1180         if (size >= sizeof (*bpop)) {
1181                 (void) printf("\t\tnum_freed = %llu\n",
1182                     (u_longlong_t)bpop->bpo_num_freed);
1183         }
1184
1185         if (dump_opt['d'] < 5)
1186                 return;
1187
1188         for (i = 0; i < bpop->bpo_num_blkptrs; i++) {
1189                 char blkbuf[BP_SPRINTF_LEN];
1190                 blkptr_t bp;
1191
1192                 int err = dmu_read(os, object,
1193                     i * sizeof (bp), sizeof (bp), &bp, 0);
1194                 if (err != 0) {
1195                         (void) printf("got error %u from dmu_read\n", err);
1196                         break;
1197                 }
1198                 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), &bp,
1199                     BP_GET_FREE(&bp));
1200                 (void) printf("\t%s\n", blkbuf);
1201         }
1202 }
1203
1204 /* ARGSUSED */
1205 static void
1206 dump_bpobj_subobjs(objset_t *os, uint64_t object, void *data, size_t size)
1207 {
1208         dmu_object_info_t doi;
1209         int64_t i;
1210
1211         VERIFY0(dmu_object_info(os, object, &doi));
1212         uint64_t *subobjs = kmem_alloc(doi.doi_max_offset, KM_SLEEP);
1213
1214         int err = dmu_read(os, object, 0, doi.doi_max_offset, subobjs, 0);
1215         if (err != 0) {
1216                 (void) printf("got error %u from dmu_read\n", err);
1217                 kmem_free(subobjs, doi.doi_max_offset);
1218                 return;
1219         }
1220
1221         int64_t last_nonzero = -1;
1222         for (i = 0; i < doi.doi_max_offset / 8; i++) {
1223                 if (subobjs[i] != 0)
1224                         last_nonzero = i;
1225         }
1226
1227         for (i = 0; i <= last_nonzero; i++) {
1228                 (void) printf("\t%llu\n", (u_longlong_t)subobjs[i]);
1229         }
1230         kmem_free(subobjs, doi.doi_max_offset);
1231 }
1232
1233 /*ARGSUSED*/
1234 static void
1235 dump_ddt_zap(objset_t *os, uint64_t object, void *data, size_t size)
1236 {
1237         dump_zap_stats(os, object);
1238         /* contents are printed elsewhere, properly decoded */
1239 }
1240
1241 /*ARGSUSED*/
1242 static void
1243 dump_sa_attrs(objset_t *os, uint64_t object, void *data, size_t size)
1244 {
1245         zap_cursor_t zc;
1246         zap_attribute_t attr;
1247
1248         dump_zap_stats(os, object);
1249         (void) printf("\n");
1250
1251         for (zap_cursor_init(&zc, os, object);
1252             zap_cursor_retrieve(&zc, &attr) == 0;
1253             zap_cursor_advance(&zc)) {
1254                 (void) printf("\t\t%s = ", attr.za_name);
1255                 if (attr.za_num_integers == 0) {
1256                         (void) printf("\n");
1257                         continue;
1258                 }
1259                 (void) printf(" %llx : [%d:%d:%d]\n",
1260                     (u_longlong_t)attr.za_first_integer,
1261                     (int)ATTR_LENGTH(attr.za_first_integer),
1262                     (int)ATTR_BSWAP(attr.za_first_integer),
1263                     (int)ATTR_NUM(attr.za_first_integer));
1264         }
1265         zap_cursor_fini(&zc);
1266 }
1267
1268 /*ARGSUSED*/
1269 static void
1270 dump_sa_layouts(objset_t *os, uint64_t object, void *data, size_t size)
1271 {
1272         zap_cursor_t zc;
1273         zap_attribute_t attr;
1274         uint16_t *layout_attrs;
1275         unsigned i;
1276
1277         dump_zap_stats(os, object);
1278         (void) printf("\n");
1279
1280         for (zap_cursor_init(&zc, os, object);
1281             zap_cursor_retrieve(&zc, &attr) == 0;
1282             zap_cursor_advance(&zc)) {
1283                 (void) printf("\t\t%s = [", attr.za_name);
1284                 if (attr.za_num_integers == 0) {
1285                         (void) printf("\n");
1286                         continue;
1287                 }
1288
1289                 VERIFY(attr.za_integer_length == 2);
1290                 layout_attrs = umem_zalloc(attr.za_num_integers *
1291                     attr.za_integer_length, UMEM_NOFAIL);
1292
1293                 VERIFY(zap_lookup(os, object, attr.za_name,
1294                     attr.za_integer_length,
1295                     attr.za_num_integers, layout_attrs) == 0);
1296
1297                 for (i = 0; i != attr.za_num_integers; i++)
1298                         (void) printf(" %d ", (int)layout_attrs[i]);
1299                 (void) printf("]\n");
1300                 umem_free(layout_attrs,
1301                     attr.za_num_integers * attr.za_integer_length);
1302         }
1303         zap_cursor_fini(&zc);
1304 }
1305
1306 /*ARGSUSED*/
1307 static void
1308 dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
1309 {
1310         zap_cursor_t zc;
1311         zap_attribute_t attr;
1312         const char *typenames[] = {
1313                 /* 0 */ "not specified",
1314                 /* 1 */ "FIFO",
1315                 /* 2 */ "Character Device",
1316                 /* 3 */ "3 (invalid)",
1317                 /* 4 */ "Directory",
1318                 /* 5 */ "5 (invalid)",
1319                 /* 6 */ "Block Device",
1320                 /* 7 */ "7 (invalid)",
1321                 /* 8 */ "Regular File",
1322                 /* 9 */ "9 (invalid)",
1323                 /* 10 */ "Symbolic Link",
1324                 /* 11 */ "11 (invalid)",
1325                 /* 12 */ "Socket",
1326                 /* 13 */ "Door",
1327                 /* 14 */ "Event Port",
1328                 /* 15 */ "15 (invalid)",
1329         };
1330
1331         dump_zap_stats(os, object);
1332         (void) printf("\n");
1333
1334         for (zap_cursor_init(&zc, os, object);
1335             zap_cursor_retrieve(&zc, &attr) == 0;
1336             zap_cursor_advance(&zc)) {
1337                 (void) printf("\t\t%s = %lld (type: %s)\n",
1338                     attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
1339                     typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
1340         }
1341         zap_cursor_fini(&zc);
1342 }
1343
1344 static int
1345 get_dtl_refcount(vdev_t *vd)
1346 {
1347         int refcount = 0;
1348
1349         if (vd->vdev_ops->vdev_op_leaf) {
1350                 space_map_t *sm = vd->vdev_dtl_sm;
1351
1352                 if (sm != NULL &&
1353                     sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
1354                         return (1);
1355                 return (0);
1356         }
1357
1358         for (unsigned c = 0; c < vd->vdev_children; c++)
1359                 refcount += get_dtl_refcount(vd->vdev_child[c]);
1360         return (refcount);
1361 }
1362
1363 static int
1364 get_metaslab_refcount(vdev_t *vd)
1365 {
1366         int refcount = 0;
1367
1368         if (vd->vdev_top == vd) {
1369                 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
1370                         space_map_t *sm = vd->vdev_ms[m]->ms_sm;
1371
1372                         if (sm != NULL &&
1373                             sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
1374                                 refcount++;
1375                 }
1376         }
1377         for (unsigned c = 0; c < vd->vdev_children; c++)
1378                 refcount += get_metaslab_refcount(vd->vdev_child[c]);
1379
1380         return (refcount);
1381 }
1382
1383 static int
1384 get_obsolete_refcount(vdev_t *vd)
1385 {
1386         uint64_t obsolete_sm_object;
1387         int refcount = 0;
1388
1389         VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
1390         if (vd->vdev_top == vd && obsolete_sm_object != 0) {
1391                 dmu_object_info_t doi;
1392                 VERIFY0(dmu_object_info(vd->vdev_spa->spa_meta_objset,
1393                     obsolete_sm_object, &doi));
1394                 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
1395                         refcount++;
1396                 }
1397         } else {
1398                 ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
1399                 ASSERT3U(obsolete_sm_object, ==, 0);
1400         }
1401         for (unsigned c = 0; c < vd->vdev_children; c++) {
1402                 refcount += get_obsolete_refcount(vd->vdev_child[c]);
1403         }
1404
1405         return (refcount);
1406 }
1407
1408 static int
1409 get_prev_obsolete_spacemap_refcount(spa_t *spa)
1410 {
1411         uint64_t prev_obj =
1412             spa->spa_condensing_indirect_phys.scip_prev_obsolete_sm_object;
1413         if (prev_obj != 0) {
1414                 dmu_object_info_t doi;
1415                 VERIFY0(dmu_object_info(spa->spa_meta_objset, prev_obj, &doi));
1416                 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
1417                         return (1);
1418                 }
1419         }
1420         return (0);
1421 }
1422
1423 static int
1424 get_checkpoint_refcount(vdev_t *vd)
1425 {
1426         int refcount = 0;
1427
1428         if (vd->vdev_top == vd && vd->vdev_top_zap != 0 &&
1429             zap_contains(spa_meta_objset(vd->vdev_spa),
1430             vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) == 0)
1431                 refcount++;
1432
1433         for (uint64_t c = 0; c < vd->vdev_children; c++)
1434                 refcount += get_checkpoint_refcount(vd->vdev_child[c]);
1435
1436         return (refcount);
1437 }
1438
1439 static int
1440 get_log_spacemap_refcount(spa_t *spa)
1441 {
1442         return (avl_numnodes(&spa->spa_sm_logs_by_txg));
1443 }
1444
1445 static int
1446 verify_spacemap_refcounts(spa_t *spa)
1447 {
1448         uint64_t expected_refcount = 0;
1449         uint64_t actual_refcount;
1450
1451         (void) feature_get_refcount(spa,
1452             &spa_feature_table[SPA_FEATURE_SPACEMAP_HISTOGRAM],
1453             &expected_refcount);
1454         actual_refcount = get_dtl_refcount(spa->spa_root_vdev);
1455         actual_refcount += get_metaslab_refcount(spa->spa_root_vdev);
1456         actual_refcount += get_obsolete_refcount(spa->spa_root_vdev);
1457         actual_refcount += get_prev_obsolete_spacemap_refcount(spa);
1458         actual_refcount += get_checkpoint_refcount(spa->spa_root_vdev);
1459         actual_refcount += get_log_spacemap_refcount(spa);
1460
1461         if (expected_refcount != actual_refcount) {
1462                 (void) printf("space map refcount mismatch: expected %lld != "
1463                     "actual %lld\n",
1464                     (longlong_t)expected_refcount,
1465                     (longlong_t)actual_refcount);
1466                 return (2);
1467         }
1468         return (0);
1469 }
1470
1471 static void
1472 dump_spacemap(objset_t *os, space_map_t *sm)
1473 {
1474         const char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
1475             "INVALID", "INVALID", "INVALID", "INVALID" };
1476
1477         if (sm == NULL)
1478                 return;
1479
1480         (void) printf("space map object %llu:\n",
1481             (longlong_t)sm->sm_object);
1482         (void) printf("  smp_length = 0x%llx\n",
1483             (longlong_t)sm->sm_phys->smp_length);
1484         (void) printf("  smp_alloc = 0x%llx\n",
1485             (longlong_t)sm->sm_phys->smp_alloc);
1486
1487         if (dump_opt['d'] < 6 && dump_opt['m'] < 4)
1488                 return;
1489
1490         /*
1491          * Print out the freelist entries in both encoded and decoded form.
1492          */
1493         uint8_t mapshift = sm->sm_shift;
1494         int64_t alloc = 0;
1495         uint64_t word, entry_id = 0;
1496         for (uint64_t offset = 0; offset < space_map_length(sm);
1497             offset += sizeof (word)) {
1498
1499                 VERIFY0(dmu_read(os, space_map_object(sm), offset,
1500                     sizeof (word), &word, DMU_READ_PREFETCH));
1501
1502                 if (sm_entry_is_debug(word)) {
1503                         uint64_t de_txg = SM_DEBUG_TXG_DECODE(word);
1504                         uint64_t de_sync_pass = SM_DEBUG_SYNCPASS_DECODE(word);
1505                         if (de_txg == 0) {
1506                                 (void) printf(
1507                                     "\t    [%6llu] PADDING\n",
1508                                     (u_longlong_t)entry_id);
1509                         } else {
1510                                 (void) printf(
1511                                     "\t    [%6llu] %s: txg %llu pass %llu\n",
1512                                     (u_longlong_t)entry_id,
1513                                     ddata[SM_DEBUG_ACTION_DECODE(word)],
1514                                     (u_longlong_t)de_txg,
1515                                     (u_longlong_t)de_sync_pass);
1516                         }
1517                         entry_id++;
1518                         continue;
1519                 }
1520
1521                 uint8_t words;
1522                 char entry_type;
1523                 uint64_t entry_off, entry_run, entry_vdev = SM_NO_VDEVID;
1524
1525                 if (sm_entry_is_single_word(word)) {
1526                         entry_type = (SM_TYPE_DECODE(word) == SM_ALLOC) ?
1527                             'A' : 'F';
1528                         entry_off = (SM_OFFSET_DECODE(word) << mapshift) +
1529                             sm->sm_start;
1530                         entry_run = SM_RUN_DECODE(word) << mapshift;
1531                         words = 1;
1532                 } else {
1533                         /* it is a two-word entry so we read another word */
1534                         ASSERT(sm_entry_is_double_word(word));
1535
1536                         uint64_t extra_word;
1537                         offset += sizeof (extra_word);
1538                         VERIFY0(dmu_read(os, space_map_object(sm), offset,
1539                             sizeof (extra_word), &extra_word,
1540                             DMU_READ_PREFETCH));
1541
1542                         ASSERT3U(offset, <=, space_map_length(sm));
1543
1544                         entry_run = SM2_RUN_DECODE(word) << mapshift;
1545                         entry_vdev = SM2_VDEV_DECODE(word);
1546                         entry_type = (SM2_TYPE_DECODE(extra_word) == SM_ALLOC) ?
1547                             'A' : 'F';
1548                         entry_off = (SM2_OFFSET_DECODE(extra_word) <<
1549                             mapshift) + sm->sm_start;
1550                         words = 2;
1551                 }
1552
1553                 (void) printf("\t    [%6llu]    %c  range:"
1554                     " %010llx-%010llx  size: %06llx vdev: %06llu words: %u\n",
1555                     (u_longlong_t)entry_id,
1556                     entry_type, (u_longlong_t)entry_off,
1557                     (u_longlong_t)(entry_off + entry_run),
1558                     (u_longlong_t)entry_run,
1559                     (u_longlong_t)entry_vdev, words);
1560
1561                 if (entry_type == 'A')
1562                         alloc += entry_run;
1563                 else
1564                         alloc -= entry_run;
1565                 entry_id++;
1566         }
1567         if (alloc != space_map_allocated(sm)) {
1568                 (void) printf("space_map_object alloc (%lld) INCONSISTENT "
1569                     "with space map summary (%lld)\n",
1570                     (longlong_t)space_map_allocated(sm), (longlong_t)alloc);
1571         }
1572 }
1573
1574 static void
1575 dump_metaslab_stats(metaslab_t *msp)
1576 {
1577         char maxbuf[32];
1578         range_tree_t *rt = msp->ms_allocatable;
1579         zfs_btree_t *t = &msp->ms_allocatable_by_size;
1580         int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
1581
1582         /* max sure nicenum has enough space */
1583         CTASSERT(sizeof (maxbuf) >= NN_NUMBUF_SZ);
1584
1585         zdb_nicenum(metaslab_largest_allocatable(msp), maxbuf, sizeof (maxbuf));
1586
1587         (void) printf("\t %25s %10lu   %7s  %6s   %4s %4d%%\n",
1588             "segments", zfs_btree_numnodes(t), "maxsize", maxbuf,
1589             "freepct", free_pct);
1590         (void) printf("\tIn-memory histogram:\n");
1591         dump_histogram(rt->rt_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1592 }
1593
1594 static void
1595 dump_metaslab(metaslab_t *msp)
1596 {
1597         vdev_t *vd = msp->ms_group->mg_vd;
1598         spa_t *spa = vd->vdev_spa;
1599         space_map_t *sm = msp->ms_sm;
1600         char freebuf[32];
1601
1602         zdb_nicenum(msp->ms_size - space_map_allocated(sm), freebuf,
1603             sizeof (freebuf));
1604
1605         (void) printf(
1606             "\tmetaslab %6llu   offset %12llx   spacemap %6llu   free    %5s\n",
1607             (u_longlong_t)msp->ms_id, (u_longlong_t)msp->ms_start,
1608             (u_longlong_t)space_map_object(sm), freebuf);
1609
1610         if (dump_opt['m'] > 2 && !dump_opt['L']) {
1611                 mutex_enter(&msp->ms_lock);
1612                 VERIFY0(metaslab_load(msp));
1613                 range_tree_stat_verify(msp->ms_allocatable);
1614                 dump_metaslab_stats(msp);
1615                 metaslab_unload(msp);
1616                 mutex_exit(&msp->ms_lock);
1617         }
1618
1619         if (dump_opt['m'] > 1 && sm != NULL &&
1620             spa_feature_is_active(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
1621                 /*
1622                  * The space map histogram represents free space in chunks
1623                  * of sm_shift (i.e. bucket 0 refers to 2^sm_shift).
1624                  */
1625                 (void) printf("\tOn-disk histogram:\t\tfragmentation %llu\n",
1626                     (u_longlong_t)msp->ms_fragmentation);
1627                 dump_histogram(sm->sm_phys->smp_histogram,
1628                     SPACE_MAP_HISTOGRAM_SIZE, sm->sm_shift);
1629         }
1630
1631         ASSERT(msp->ms_size == (1ULL << vd->vdev_ms_shift));
1632         dump_spacemap(spa->spa_meta_objset, msp->ms_sm);
1633
1634         if (spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP)) {
1635                 (void) printf("\tFlush data:\n\tunflushed txg=%llu\n\n",
1636                     (u_longlong_t)metaslab_unflushed_txg(msp));
1637         }
1638 }
1639
1640 static void
1641 print_vdev_metaslab_header(vdev_t *vd)
1642 {
1643         vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
1644         const char *bias_str = "";
1645         if (alloc_bias == VDEV_BIAS_LOG || vd->vdev_islog) {
1646                 bias_str = VDEV_ALLOC_BIAS_LOG;
1647         } else if (alloc_bias == VDEV_BIAS_SPECIAL) {
1648                 bias_str = VDEV_ALLOC_BIAS_SPECIAL;
1649         } else if (alloc_bias == VDEV_BIAS_DEDUP) {
1650                 bias_str = VDEV_ALLOC_BIAS_DEDUP;
1651         }
1652
1653         uint64_t ms_flush_data_obj = 0;
1654         if (vd->vdev_top_zap != 0) {
1655                 int error = zap_lookup(spa_meta_objset(vd->vdev_spa),
1656                     vd->vdev_top_zap, VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS,
1657                     sizeof (uint64_t), 1, &ms_flush_data_obj);
1658                 if (error != ENOENT) {
1659                         ASSERT0(error);
1660                 }
1661         }
1662
1663         (void) printf("\tvdev %10llu   %s",
1664             (u_longlong_t)vd->vdev_id, bias_str);
1665
1666         if (ms_flush_data_obj != 0) {
1667                 (void) printf("   ms_unflushed_phys object %llu",
1668                     (u_longlong_t)ms_flush_data_obj);
1669         }
1670
1671         (void) printf("\n\t%-10s%5llu   %-19s   %-15s   %-12s\n",
1672             "metaslabs", (u_longlong_t)vd->vdev_ms_count,
1673             "offset", "spacemap", "free");
1674         (void) printf("\t%15s   %19s   %15s   %12s\n",
1675             "---------------", "-------------------",
1676             "---------------", "------------");
1677 }
1678
1679 static void
1680 dump_metaslab_groups(spa_t *spa)
1681 {
1682         vdev_t *rvd = spa->spa_root_vdev;
1683         metaslab_class_t *mc = spa_normal_class(spa);
1684         uint64_t fragmentation;
1685
1686         metaslab_class_histogram_verify(mc);
1687
1688         for (unsigned c = 0; c < rvd->vdev_children; c++) {
1689                 vdev_t *tvd = rvd->vdev_child[c];
1690                 metaslab_group_t *mg = tvd->vdev_mg;
1691
1692                 if (mg == NULL || mg->mg_class != mc)
1693                         continue;
1694
1695                 metaslab_group_histogram_verify(mg);
1696                 mg->mg_fragmentation = metaslab_group_fragmentation(mg);
1697
1698                 (void) printf("\tvdev %10llu\t\tmetaslabs%5llu\t\t"
1699                     "fragmentation",
1700                     (u_longlong_t)tvd->vdev_id,
1701                     (u_longlong_t)tvd->vdev_ms_count);
1702                 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
1703                         (void) printf("%3s\n", "-");
1704                 } else {
1705                         (void) printf("%3llu%%\n",
1706                             (u_longlong_t)mg->mg_fragmentation);
1707                 }
1708                 dump_histogram(mg->mg_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1709         }
1710
1711         (void) printf("\tpool %s\tfragmentation", spa_name(spa));
1712         fragmentation = metaslab_class_fragmentation(mc);
1713         if (fragmentation == ZFS_FRAG_INVALID)
1714                 (void) printf("\t%3s\n", "-");
1715         else
1716                 (void) printf("\t%3llu%%\n", (u_longlong_t)fragmentation);
1717         dump_histogram(mc->mc_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1718 }
1719
1720 static void
1721 print_vdev_indirect(vdev_t *vd)
1722 {
1723         vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
1724         vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
1725         vdev_indirect_births_t *vib = vd->vdev_indirect_births;
1726
1727         if (vim == NULL) {
1728                 ASSERT3P(vib, ==, NULL);
1729                 return;
1730         }
1731
1732         ASSERT3U(vdev_indirect_mapping_object(vim), ==,
1733             vic->vic_mapping_object);
1734         ASSERT3U(vdev_indirect_births_object(vib), ==,
1735             vic->vic_births_object);
1736
1737         (void) printf("indirect births obj %llu:\n",
1738             (longlong_t)vic->vic_births_object);
1739         (void) printf("    vib_count = %llu\n",
1740             (longlong_t)vdev_indirect_births_count(vib));
1741         for (uint64_t i = 0; i < vdev_indirect_births_count(vib); i++) {
1742                 vdev_indirect_birth_entry_phys_t *cur_vibe =
1743                     &vib->vib_entries[i];
1744                 (void) printf("\toffset %llx -> txg %llu\n",
1745                     (longlong_t)cur_vibe->vibe_offset,
1746                     (longlong_t)cur_vibe->vibe_phys_birth_txg);
1747         }
1748         (void) printf("\n");
1749
1750         (void) printf("indirect mapping obj %llu:\n",
1751             (longlong_t)vic->vic_mapping_object);
1752         (void) printf("    vim_max_offset = 0x%llx\n",
1753             (longlong_t)vdev_indirect_mapping_max_offset(vim));
1754         (void) printf("    vim_bytes_mapped = 0x%llx\n",
1755             (longlong_t)vdev_indirect_mapping_bytes_mapped(vim));
1756         (void) printf("    vim_count = %llu\n",
1757             (longlong_t)vdev_indirect_mapping_num_entries(vim));
1758
1759         if (dump_opt['d'] <= 5 && dump_opt['m'] <= 3)
1760                 return;
1761
1762         uint32_t *counts = vdev_indirect_mapping_load_obsolete_counts(vim);
1763
1764         for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
1765                 vdev_indirect_mapping_entry_phys_t *vimep =
1766                     &vim->vim_entries[i];
1767                 (void) printf("\t<%llx:%llx:%llx> -> "
1768                     "<%llx:%llx:%llx> (%x obsolete)\n",
1769                     (longlong_t)vd->vdev_id,
1770                     (longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
1771                     (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1772                     (longlong_t)DVA_GET_VDEV(&vimep->vimep_dst),
1773                     (longlong_t)DVA_GET_OFFSET(&vimep->vimep_dst),
1774                     (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1775                     counts[i]);
1776         }
1777         (void) printf("\n");
1778
1779         uint64_t obsolete_sm_object;
1780         VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
1781         if (obsolete_sm_object != 0) {
1782                 objset_t *mos = vd->vdev_spa->spa_meta_objset;
1783                 (void) printf("obsolete space map object %llu:\n",
1784                     (u_longlong_t)obsolete_sm_object);
1785                 ASSERT(vd->vdev_obsolete_sm != NULL);
1786                 ASSERT3U(space_map_object(vd->vdev_obsolete_sm), ==,
1787                     obsolete_sm_object);
1788                 dump_spacemap(mos, vd->vdev_obsolete_sm);
1789                 (void) printf("\n");
1790         }
1791 }
1792
1793 static void
1794 dump_metaslabs(spa_t *spa)
1795 {
1796         vdev_t *vd, *rvd = spa->spa_root_vdev;
1797         uint64_t m, c = 0, children = rvd->vdev_children;
1798
1799         (void) printf("\nMetaslabs:\n");
1800
1801         if (!dump_opt['d'] && zopt_metaslab_args > 0) {
1802                 c = zopt_metaslab[0];
1803
1804                 if (c >= children)
1805                         (void) fatal("bad vdev id: %llu", (u_longlong_t)c);
1806
1807                 if (zopt_metaslab_args > 1) {
1808                         vd = rvd->vdev_child[c];
1809                         print_vdev_metaslab_header(vd);
1810
1811                         for (m = 1; m < zopt_metaslab_args; m++) {
1812                                 if (zopt_metaslab[m] < vd->vdev_ms_count)
1813                                         dump_metaslab(
1814                                             vd->vdev_ms[zopt_metaslab[m]]);
1815                                 else
1816                                         (void) fprintf(stderr, "bad metaslab "
1817                                             "number %llu\n",
1818                                             (u_longlong_t)zopt_metaslab[m]);
1819                         }
1820                         (void) printf("\n");
1821                         return;
1822                 }
1823                 children = c + 1;
1824         }
1825         for (; c < children; c++) {
1826                 vd = rvd->vdev_child[c];
1827                 print_vdev_metaslab_header(vd);
1828
1829                 print_vdev_indirect(vd);
1830
1831                 for (m = 0; m < vd->vdev_ms_count; m++)
1832                         dump_metaslab(vd->vdev_ms[m]);
1833                 (void) printf("\n");
1834         }
1835 }
1836
1837 static void
1838 dump_log_spacemaps(spa_t *spa)
1839 {
1840         if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
1841                 return;
1842
1843         (void) printf("\nLog Space Maps in Pool:\n");
1844         for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
1845             sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls)) {
1846                 space_map_t *sm = NULL;
1847                 VERIFY0(space_map_open(&sm, spa_meta_objset(spa),
1848                     sls->sls_sm_obj, 0, UINT64_MAX, SPA_MINBLOCKSHIFT));
1849
1850                 (void) printf("Log Spacemap object %llu txg %llu\n",
1851                     (u_longlong_t)sls->sls_sm_obj, (u_longlong_t)sls->sls_txg);
1852                 dump_spacemap(spa->spa_meta_objset, sm);
1853                 space_map_close(sm);
1854         }
1855         (void) printf("\n");
1856 }
1857
1858 static void
1859 dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
1860 {
1861         const ddt_phys_t *ddp = dde->dde_phys;
1862         const ddt_key_t *ddk = &dde->dde_key;
1863         const char *types[4] = { "ditto", "single", "double", "triple" };
1864         char blkbuf[BP_SPRINTF_LEN];
1865         blkptr_t blk;
1866         int p;
1867
1868         for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1869                 if (ddp->ddp_phys_birth == 0)
1870                         continue;
1871                 ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
1872                 snprintf_blkptr(blkbuf, sizeof (blkbuf), &blk);
1873                 (void) printf("index %llx refcnt %llu %s %s\n",
1874                     (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
1875                     types[p], blkbuf);
1876         }
1877 }
1878
1879 static void
1880 dump_dedup_ratio(const ddt_stat_t *dds)
1881 {
1882         double rL, rP, rD, D, dedup, compress, copies;
1883
1884         if (dds->dds_blocks == 0)
1885                 return;
1886
1887         rL = (double)dds->dds_ref_lsize;
1888         rP = (double)dds->dds_ref_psize;
1889         rD = (double)dds->dds_ref_dsize;
1890         D = (double)dds->dds_dsize;
1891
1892         dedup = rD / D;
1893         compress = rL / rP;
1894         copies = rD / rP;
1895
1896         (void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
1897             "dedup * compress / copies = %.2f\n\n",
1898             dedup, compress, copies, dedup * compress / copies);
1899 }
1900
1901 static void
1902 dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
1903 {
1904         char name[DDT_NAMELEN];
1905         ddt_entry_t dde;
1906         uint64_t walk = 0;
1907         dmu_object_info_t doi;
1908         uint64_t count, dspace, mspace;
1909         int error;
1910
1911         error = ddt_object_info(ddt, type, class, &doi);
1912
1913         if (error == ENOENT)
1914                 return;
1915         ASSERT(error == 0);
1916
1917         error = ddt_object_count(ddt, type, class, &count);
1918         ASSERT(error == 0);
1919         if (count == 0)
1920                 return;
1921
1922         dspace = doi.doi_physical_blocks_512 << 9;
1923         mspace = doi.doi_fill_count * doi.doi_data_block_size;
1924
1925         ddt_object_name(ddt, type, class, name);
1926
1927         (void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
1928             name,
1929             (u_longlong_t)count,
1930             (u_longlong_t)(dspace / count),
1931             (u_longlong_t)(mspace / count));
1932
1933         if (dump_opt['D'] < 3)
1934                 return;
1935
1936         zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
1937
1938         if (dump_opt['D'] < 4)
1939                 return;
1940
1941         if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
1942                 return;
1943
1944         (void) printf("%s contents:\n\n", name);
1945
1946         while ((error = ddt_object_walk(ddt, type, class, &walk, &dde)) == 0)
1947                 dump_dde(ddt, &dde, walk);
1948
1949         ASSERT3U(error, ==, ENOENT);
1950
1951         (void) printf("\n");
1952 }
1953
1954 static void
1955 dump_all_ddts(spa_t *spa)
1956 {
1957         ddt_histogram_t ddh_total;
1958         ddt_stat_t dds_total;
1959
1960         bzero(&ddh_total, sizeof (ddh_total));
1961         bzero(&dds_total, sizeof (dds_total));
1962
1963         for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1964                 ddt_t *ddt = spa->spa_ddt[c];
1965                 for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
1966                         for (enum ddt_class class = 0; class < DDT_CLASSES;
1967                             class++) {
1968                                 dump_ddt(ddt, type, class);
1969                         }
1970                 }
1971         }
1972
1973         ddt_get_dedup_stats(spa, &dds_total);
1974
1975         if (dds_total.dds_blocks == 0) {
1976                 (void) printf("All DDTs are empty\n");
1977                 return;
1978         }
1979
1980         (void) printf("\n");
1981
1982         if (dump_opt['D'] > 1) {
1983                 (void) printf("DDT histogram (aggregated over all DDTs):\n");
1984                 ddt_get_dedup_histogram(spa, &ddh_total);
1985                 zpool_dump_ddt(&dds_total, &ddh_total);
1986         }
1987
1988         dump_dedup_ratio(&dds_total);
1989 }
1990
1991 static void
1992 dump_dtl_seg(void *arg, uint64_t start, uint64_t size)
1993 {
1994         char *prefix = arg;
1995
1996         (void) printf("%s [%llu,%llu) length %llu\n",
1997             prefix,
1998             (u_longlong_t)start,
1999             (u_longlong_t)(start + size),
2000             (u_longlong_t)(size));
2001 }
2002
2003 static void
2004 dump_dtl(vdev_t *vd, int indent)
2005 {
2006         spa_t *spa = vd->vdev_spa;
2007         boolean_t required;
2008         const char *name[DTL_TYPES] = { "missing", "partial", "scrub",
2009                 "outage" };
2010         char prefix[256];
2011
2012         spa_vdev_state_enter(spa, SCL_NONE);
2013         required = vdev_dtl_required(vd);
2014         (void) spa_vdev_state_exit(spa, NULL, 0);
2015
2016         if (indent == 0)
2017                 (void) printf("\nDirty time logs:\n\n");
2018
2019         (void) printf("\t%*s%s [%s]\n", indent, "",
2020             vd->vdev_path ? vd->vdev_path :
2021             vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
2022             required ? "DTL-required" : "DTL-expendable");
2023
2024         for (int t = 0; t < DTL_TYPES; t++) {
2025                 range_tree_t *rt = vd->vdev_dtl[t];
2026                 if (range_tree_space(rt) == 0)
2027                         continue;
2028                 (void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
2029                     indent + 2, "", name[t]);
2030                 range_tree_walk(rt, dump_dtl_seg, prefix);
2031                 if (dump_opt['d'] > 5 && vd->vdev_children == 0)
2032                         dump_spacemap(spa->spa_meta_objset,
2033                             vd->vdev_dtl_sm);
2034         }
2035
2036         for (unsigned c = 0; c < vd->vdev_children; c++)
2037                 dump_dtl(vd->vdev_child[c], indent + 4);
2038 }
2039
2040 static void
2041 dump_history(spa_t *spa)
2042 {
2043         nvlist_t **events = NULL;
2044         char *buf;
2045         uint64_t resid, len, off = 0;
2046         uint_t num = 0;
2047         int error;
2048         time_t tsec;
2049         struct tm t;
2050         char tbuf[30];
2051         char internalstr[MAXPATHLEN];
2052
2053         if ((buf = malloc(SPA_OLD_MAXBLOCKSIZE)) == NULL) {
2054                 (void) fprintf(stderr, "%s: unable to allocate I/O buffer\n",
2055                     __func__);
2056                 return;
2057         }
2058
2059         do {
2060                 len = SPA_OLD_MAXBLOCKSIZE;
2061
2062                 if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
2063                         (void) fprintf(stderr, "Unable to read history: "
2064                             "error %d\n", error);
2065                         free(buf);
2066                         return;
2067                 }
2068
2069                 if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
2070                         break;
2071
2072                 off -= resid;
2073         } while (len != 0);
2074
2075         (void) printf("\nHistory:\n");
2076         for (unsigned i = 0; i < num; i++) {
2077                 uint64_t time, txg, ievent;
2078                 char *cmd, *intstr;
2079                 boolean_t printed = B_FALSE;
2080
2081                 if (nvlist_lookup_uint64(events[i], ZPOOL_HIST_TIME,
2082                     &time) != 0)
2083                         goto next;
2084                 if (nvlist_lookup_string(events[i], ZPOOL_HIST_CMD,
2085                     &cmd) != 0) {
2086                         if (nvlist_lookup_uint64(events[i],
2087                             ZPOOL_HIST_INT_EVENT, &ievent) != 0)
2088                                 goto next;
2089                         verify(nvlist_lookup_uint64(events[i],
2090                             ZPOOL_HIST_TXG, &txg) == 0);
2091                         verify(nvlist_lookup_string(events[i],
2092                             ZPOOL_HIST_INT_STR, &intstr) == 0);
2093                         if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
2094                                 goto next;
2095
2096                         (void) snprintf(internalstr,
2097                             sizeof (internalstr),
2098                             "[internal %s txg:%lld] %s",
2099                             zfs_history_event_names[ievent],
2100                             (longlong_t)txg, intstr);
2101                         cmd = internalstr;
2102                 }
2103                 tsec = time;
2104                 (void) localtime_r(&tsec, &t);
2105                 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
2106                 (void) printf("%s %s\n", tbuf, cmd);
2107                 printed = B_TRUE;
2108
2109 next:
2110                 if (dump_opt['h'] > 1) {
2111                         if (!printed)
2112                                 (void) printf("unrecognized record:\n");
2113                         dump_nvlist(events[i], 2);
2114                 }
2115         }
2116         free(buf);
2117 }
2118
2119 /*ARGSUSED*/
2120 static void
2121 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
2122 {
2123 }
2124
2125 static uint64_t
2126 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp,
2127     const zbookmark_phys_t *zb)
2128 {
2129         if (dnp == NULL) {
2130                 ASSERT(zb->zb_level < 0);
2131                 if (zb->zb_object == 0)
2132                         return (zb->zb_blkid);
2133                 return (zb->zb_blkid * BP_GET_LSIZE(bp));
2134         }
2135
2136         ASSERT(zb->zb_level >= 0);
2137
2138         return ((zb->zb_blkid <<
2139             (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
2140             dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
2141 }
2142
2143 static void
2144 snprintf_zstd_header(spa_t *spa, char *blkbuf, size_t buflen,
2145     const blkptr_t *bp)
2146 {
2147         abd_t *pabd;
2148         void *buf;
2149         zio_t *zio;
2150         zfs_zstdhdr_t zstd_hdr;
2151         int error;
2152
2153         if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_ZSTD)
2154                 return;
2155
2156         if (BP_IS_HOLE(bp))
2157                 return;
2158
2159         if (BP_IS_EMBEDDED(bp)) {
2160                 buf = malloc(SPA_MAXBLOCKSIZE);
2161                 if (buf == NULL) {
2162                         (void) fprintf(stderr, "out of memory\n");
2163                         exit(1);
2164                 }
2165                 decode_embedded_bp_compressed(bp, buf);
2166                 memcpy(&zstd_hdr, buf, sizeof (zstd_hdr));
2167                 free(buf);
2168                 zstd_hdr.c_len = BE_32(zstd_hdr.c_len);
2169                 zstd_hdr.raw_version_level = BE_32(zstd_hdr.raw_version_level);
2170                 (void) snprintf(blkbuf + strlen(blkbuf),
2171                     buflen - strlen(blkbuf),
2172                     " ZSTD:size=%u:version=%u:level=%u:EMBEDDED",
2173                     zstd_hdr.c_len, zstd_hdr.version, zstd_hdr.level);
2174                 return;
2175         }
2176
2177         pabd = abd_alloc_for_io(SPA_MAXBLOCKSIZE, B_FALSE);
2178         zio = zio_root(spa, NULL, NULL, 0);
2179
2180         /* Decrypt but don't decompress so we can read the compression header */
2181         zio_nowait(zio_read(zio, spa, bp, pabd, BP_GET_PSIZE(bp), NULL, NULL,
2182             ZIO_PRIORITY_SYNC_READ, ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW_COMPRESS,
2183             NULL));
2184         error = zio_wait(zio);
2185         if (error) {
2186                 (void) fprintf(stderr, "read failed: %d\n", error);
2187                 return;
2188         }
2189         buf = abd_borrow_buf_copy(pabd, BP_GET_LSIZE(bp));
2190         memcpy(&zstd_hdr, buf, sizeof (zstd_hdr));
2191         zstd_hdr.c_len = BE_32(zstd_hdr.c_len);
2192         zstd_hdr.raw_version_level = BE_32(zstd_hdr.raw_version_level);
2193
2194         (void) snprintf(blkbuf + strlen(blkbuf),
2195             buflen - strlen(blkbuf),
2196             " ZSTD:size=%u:version=%u:level=%u:NORMAL",
2197             zstd_hdr.c_len, zstd_hdr.version, zstd_hdr.level);
2198
2199         abd_return_buf_copy(pabd, buf, BP_GET_LSIZE(bp));
2200 }
2201
2202 static void
2203 snprintf_blkptr_compact(char *blkbuf, size_t buflen, const blkptr_t *bp,
2204     boolean_t bp_freed)
2205 {
2206         const dva_t *dva = bp->blk_dva;
2207         int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
2208         int i;
2209
2210         if (dump_opt['b'] >= 6) {
2211                 snprintf_blkptr(blkbuf, buflen, bp);
2212                 if (bp_freed) {
2213                         (void) snprintf(blkbuf + strlen(blkbuf),
2214                             buflen - strlen(blkbuf), " %s", "FREE");
2215                 }
2216                 return;
2217         }
2218
2219         if (BP_IS_EMBEDDED(bp)) {
2220                 (void) sprintf(blkbuf,
2221                     "EMBEDDED et=%u %llxL/%llxP B=%llu",
2222                     (int)BPE_GET_ETYPE(bp),
2223                     (u_longlong_t)BPE_GET_LSIZE(bp),
2224                     (u_longlong_t)BPE_GET_PSIZE(bp),
2225                     (u_longlong_t)bp->blk_birth);
2226                 return;
2227         }
2228
2229         blkbuf[0] = '\0';
2230
2231         for (i = 0; i < ndvas; i++)
2232                 (void) snprintf(blkbuf + strlen(blkbuf),
2233                     buflen - strlen(blkbuf), "%llu:%llx:%llx ",
2234                     (u_longlong_t)DVA_GET_VDEV(&dva[i]),
2235                     (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
2236                     (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
2237
2238         if (BP_IS_HOLE(bp)) {
2239                 (void) snprintf(blkbuf + strlen(blkbuf),
2240                     buflen - strlen(blkbuf),
2241                     "%llxL B=%llu",
2242                     (u_longlong_t)BP_GET_LSIZE(bp),
2243                     (u_longlong_t)bp->blk_birth);
2244         } else {
2245                 (void) snprintf(blkbuf + strlen(blkbuf),
2246                     buflen - strlen(blkbuf),
2247                     "%llxL/%llxP F=%llu B=%llu/%llu",
2248                     (u_longlong_t)BP_GET_LSIZE(bp),
2249                     (u_longlong_t)BP_GET_PSIZE(bp),
2250                     (u_longlong_t)BP_GET_FILL(bp),
2251                     (u_longlong_t)bp->blk_birth,
2252                     (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
2253                 if (bp_freed)
2254                         (void) snprintf(blkbuf + strlen(blkbuf),
2255                             buflen - strlen(blkbuf), " %s", "FREE");
2256                 (void) snprintf(blkbuf + strlen(blkbuf),
2257                     buflen - strlen(blkbuf), " cksum=%llx:%llx:%llx:%llx",
2258                     (u_longlong_t)bp->blk_cksum.zc_word[0],
2259                     (u_longlong_t)bp->blk_cksum.zc_word[1],
2260                     (u_longlong_t)bp->blk_cksum.zc_word[2],
2261                     (u_longlong_t)bp->blk_cksum.zc_word[3]);
2262         }
2263 }
2264
2265 static void
2266 print_indirect(spa_t *spa, blkptr_t *bp, const zbookmark_phys_t *zb,
2267     const dnode_phys_t *dnp)
2268 {
2269         char blkbuf[BP_SPRINTF_LEN];
2270         int l;
2271
2272         if (!BP_IS_EMBEDDED(bp)) {
2273                 ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
2274                 ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
2275         }
2276
2277         (void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
2278
2279         ASSERT(zb->zb_level >= 0);
2280
2281         for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
2282                 if (l == zb->zb_level) {
2283                         (void) printf("L%llx", (u_longlong_t)zb->zb_level);
2284                 } else {
2285                         (void) printf(" ");
2286                 }
2287         }
2288
2289         snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp, B_FALSE);
2290         if (dump_opt['Z'] && BP_GET_COMPRESS(bp) == ZIO_COMPRESS_ZSTD)
2291                 snprintf_zstd_header(spa, blkbuf, sizeof (blkbuf), bp);
2292         (void) printf("%s\n", blkbuf);
2293 }
2294
2295 static int
2296 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
2297     blkptr_t *bp, const zbookmark_phys_t *zb)
2298 {
2299         int err = 0;
2300
2301         if (bp->blk_birth == 0)
2302                 return (0);
2303
2304         print_indirect(spa, bp, zb, dnp);
2305
2306         if (BP_GET_LEVEL(bp) > 0 && !BP_IS_HOLE(bp)) {
2307                 arc_flags_t flags = ARC_FLAG_WAIT;
2308                 int i;
2309                 blkptr_t *cbp;
2310                 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
2311                 arc_buf_t *buf;
2312                 uint64_t fill = 0;
2313                 ASSERT(!BP_IS_REDACTED(bp));
2314
2315                 err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
2316                     ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
2317                 if (err)
2318                         return (err);
2319                 ASSERT(buf->b_data);
2320
2321                 /* recursively visit blocks below this */
2322                 cbp = buf->b_data;
2323                 for (i = 0; i < epb; i++, cbp++) {
2324                         zbookmark_phys_t czb;
2325
2326                         SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
2327                             zb->zb_level - 1,
2328                             zb->zb_blkid * epb + i);
2329                         err = visit_indirect(spa, dnp, cbp, &czb);
2330                         if (err)
2331                                 break;
2332                         fill += BP_GET_FILL(cbp);
2333                 }
2334                 if (!err)
2335                         ASSERT3U(fill, ==, BP_GET_FILL(bp));
2336                 arc_buf_destroy(buf, &buf);
2337         }
2338
2339         return (err);
2340 }
2341
2342 /*ARGSUSED*/
2343 static void
2344 dump_indirect(dnode_t *dn)
2345 {
2346         dnode_phys_t *dnp = dn->dn_phys;
2347         int j;
2348         zbookmark_phys_t czb;
2349
2350         (void) printf("Indirect blocks:\n");
2351
2352         SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
2353             dn->dn_object, dnp->dn_nlevels - 1, 0);
2354         for (j = 0; j < dnp->dn_nblkptr; j++) {
2355                 czb.zb_blkid = j;
2356                 (void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
2357                     &dnp->dn_blkptr[j], &czb);
2358         }
2359
2360         (void) printf("\n");
2361 }
2362
2363 /*ARGSUSED*/
2364 static void
2365 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
2366 {
2367         dsl_dir_phys_t *dd = data;
2368         time_t crtime;
2369         char nice[32];
2370
2371         /* make sure nicenum has enough space */
2372         CTASSERT(sizeof (nice) >= NN_NUMBUF_SZ);
2373
2374         if (dd == NULL)
2375                 return;
2376
2377         ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
2378
2379         crtime = dd->dd_creation_time;
2380         (void) printf("\t\tcreation_time = %s", ctime(&crtime));
2381         (void) printf("\t\thead_dataset_obj = %llu\n",
2382             (u_longlong_t)dd->dd_head_dataset_obj);
2383         (void) printf("\t\tparent_dir_obj = %llu\n",
2384             (u_longlong_t)dd->dd_parent_obj);
2385         (void) printf("\t\torigin_obj = %llu\n",
2386             (u_longlong_t)dd->dd_origin_obj);
2387         (void) printf("\t\tchild_dir_zapobj = %llu\n",
2388             (u_longlong_t)dd->dd_child_dir_zapobj);
2389         zdb_nicenum(dd->dd_used_bytes, nice, sizeof (nice));
2390         (void) printf("\t\tused_bytes = %s\n", nice);
2391         zdb_nicenum(dd->dd_compressed_bytes, nice, sizeof (nice));
2392         (void) printf("\t\tcompressed_bytes = %s\n", nice);
2393         zdb_nicenum(dd->dd_uncompressed_bytes, nice, sizeof (nice));
2394         (void) printf("\t\tuncompressed_bytes = %s\n", nice);
2395         zdb_nicenum(dd->dd_quota, nice, sizeof (nice));
2396         (void) printf("\t\tquota = %s\n", nice);
2397         zdb_nicenum(dd->dd_reserved, nice, sizeof (nice));
2398         (void) printf("\t\treserved = %s\n", nice);
2399         (void) printf("\t\tprops_zapobj = %llu\n",
2400             (u_longlong_t)dd->dd_props_zapobj);
2401         (void) printf("\t\tdeleg_zapobj = %llu\n",
2402             (u_longlong_t)dd->dd_deleg_zapobj);
2403         (void) printf("\t\tflags = %llx\n",
2404             (u_longlong_t)dd->dd_flags);
2405
2406 #define DO(which) \
2407         zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice, \
2408             sizeof (nice)); \
2409         (void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
2410         DO(HEAD);
2411         DO(SNAP);
2412         DO(CHILD);
2413         DO(CHILD_RSRV);
2414         DO(REFRSRV);
2415 #undef DO
2416         (void) printf("\t\tclones = %llu\n",
2417             (u_longlong_t)dd->dd_clones);
2418 }
2419
2420 /*ARGSUSED*/
2421 static void
2422 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
2423 {
2424         dsl_dataset_phys_t *ds = data;
2425         time_t crtime;
2426         char used[32], compressed[32], uncompressed[32], unique[32];
2427         char blkbuf[BP_SPRINTF_LEN];
2428
2429         /* make sure nicenum has enough space */
2430         CTASSERT(sizeof (used) >= NN_NUMBUF_SZ);
2431         CTASSERT(sizeof (compressed) >= NN_NUMBUF_SZ);
2432         CTASSERT(sizeof (uncompressed) >= NN_NUMBUF_SZ);
2433         CTASSERT(sizeof (unique) >= NN_NUMBUF_SZ);
2434
2435         if (ds == NULL)
2436                 return;
2437
2438         ASSERT(size == sizeof (*ds));
2439         crtime = ds->ds_creation_time;
2440         zdb_nicenum(ds->ds_referenced_bytes, used, sizeof (used));
2441         zdb_nicenum(ds->ds_compressed_bytes, compressed, sizeof (compressed));
2442         zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed,
2443             sizeof (uncompressed));
2444         zdb_nicenum(ds->ds_unique_bytes, unique, sizeof (unique));
2445         snprintf_blkptr(blkbuf, sizeof (blkbuf), &ds->ds_bp);
2446
2447         (void) printf("\t\tdir_obj = %llu\n",
2448             (u_longlong_t)ds->ds_dir_obj);
2449         (void) printf("\t\tprev_snap_obj = %llu\n",
2450             (u_longlong_t)ds->ds_prev_snap_obj);
2451         (void) printf("\t\tprev_snap_txg = %llu\n",
2452             (u_longlong_t)ds->ds_prev_snap_txg);
2453         (void) printf("\t\tnext_snap_obj = %llu\n",
2454             (u_longlong_t)ds->ds_next_snap_obj);
2455         (void) printf("\t\tsnapnames_zapobj = %llu\n",
2456             (u_longlong_t)ds->ds_snapnames_zapobj);
2457         (void) printf("\t\tnum_children = %llu\n",
2458             (u_longlong_t)ds->ds_num_children);
2459         (void) printf("\t\tuserrefs_obj = %llu\n",
2460             (u_longlong_t)ds->ds_userrefs_obj);
2461         (void) printf("\t\tcreation_time = %s", ctime(&crtime));
2462         (void) printf("\t\tcreation_txg = %llu\n",
2463             (u_longlong_t)ds->ds_creation_txg);
2464         (void) printf("\t\tdeadlist_obj = %llu\n",
2465             (u_longlong_t)ds->ds_deadlist_obj);
2466         (void) printf("\t\tused_bytes = %s\n", used);
2467         (void) printf("\t\tcompressed_bytes = %s\n", compressed);
2468         (void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
2469         (void) printf("\t\tunique = %s\n", unique);
2470         (void) printf("\t\tfsid_guid = %llu\n",
2471             (u_longlong_t)ds->ds_fsid_guid);
2472         (void) printf("\t\tguid = %llu\n",
2473             (u_longlong_t)ds->ds_guid);
2474         (void) printf("\t\tflags = %llx\n",
2475             (u_longlong_t)ds->ds_flags);
2476         (void) printf("\t\tnext_clones_obj = %llu\n",
2477             (u_longlong_t)ds->ds_next_clones_obj);
2478         (void) printf("\t\tprops_obj = %llu\n",
2479             (u_longlong_t)ds->ds_props_obj);
2480         (void) printf("\t\tbp = %s\n", blkbuf);
2481 }
2482
2483 /* ARGSUSED */
2484 static int
2485 dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2486 {
2487         char blkbuf[BP_SPRINTF_LEN];
2488
2489         if (bp->blk_birth != 0) {
2490                 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
2491                 (void) printf("\t%s\n", blkbuf);
2492         }
2493         return (0);
2494 }
2495
2496 static void
2497 dump_bptree(objset_t *os, uint64_t obj, const char *name)
2498 {
2499         char bytes[32];
2500         bptree_phys_t *bt;
2501         dmu_buf_t *db;
2502
2503         /* make sure nicenum has enough space */
2504         CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
2505
2506         if (dump_opt['d'] < 3)
2507                 return;
2508
2509         VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
2510         bt = db->db_data;
2511         zdb_nicenum(bt->bt_bytes, bytes, sizeof (bytes));
2512         (void) printf("\n    %s: %llu datasets, %s\n",
2513             name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
2514         dmu_buf_rele(db, FTAG);
2515
2516         if (dump_opt['d'] < 5)
2517                 return;
2518
2519         (void) printf("\n");
2520
2521         (void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
2522 }
2523
2524 /* ARGSUSED */
2525 static int
2526 dump_bpobj_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed, dmu_tx_t *tx)
2527 {
2528         char blkbuf[BP_SPRINTF_LEN];
2529
2530         ASSERT(bp->blk_birth != 0);
2531         snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp, bp_freed);
2532         (void) printf("\t%s\n", blkbuf);
2533         return (0);
2534 }
2535
2536 static void
2537 dump_full_bpobj(bpobj_t *bpo, const char *name, int indent)
2538 {
2539         char bytes[32];
2540         char comp[32];
2541         char uncomp[32];
2542         uint64_t i;
2543
2544         /* make sure nicenum has enough space */
2545         CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
2546         CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
2547         CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
2548
2549         if (dump_opt['d'] < 3)
2550                 return;
2551
2552         zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes, sizeof (bytes));
2553         if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
2554                 zdb_nicenum(bpo->bpo_phys->bpo_comp, comp, sizeof (comp));
2555                 zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp, sizeof (uncomp));
2556                 if (bpo->bpo_havefreed) {
2557                         (void) printf("    %*s: object %llu, %llu local "
2558                             "blkptrs, %llu freed, %llu subobjs in object %llu, "
2559                             "%s (%s/%s comp)\n",
2560                             indent * 8, name,
2561                             (u_longlong_t)bpo->bpo_object,
2562                             (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2563                             (u_longlong_t)bpo->bpo_phys->bpo_num_freed,
2564                             (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
2565                             (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
2566                             bytes, comp, uncomp);
2567                 } else {
2568                         (void) printf("    %*s: object %llu, %llu local "
2569                             "blkptrs, %llu subobjs in object %llu, "
2570                             "%s (%s/%s comp)\n",
2571                             indent * 8, name,
2572                             (u_longlong_t)bpo->bpo_object,
2573                             (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2574                             (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
2575                             (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
2576                             bytes, comp, uncomp);
2577                 }
2578
2579                 for (i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
2580                         uint64_t subobj;
2581                         bpobj_t subbpo;
2582                         int error;
2583                         VERIFY0(dmu_read(bpo->bpo_os,
2584                             bpo->bpo_phys->bpo_subobjs,
2585                             i * sizeof (subobj), sizeof (subobj), &subobj, 0));
2586                         error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
2587                         if (error != 0) {
2588                                 (void) printf("ERROR %u while trying to open "
2589                                     "subobj id %llu\n",
2590                                     error, (u_longlong_t)subobj);
2591                                 continue;
2592                         }
2593                         dump_full_bpobj(&subbpo, "subobj", indent + 1);
2594                         bpobj_close(&subbpo);
2595                 }
2596         } else {
2597                 if (bpo->bpo_havefreed) {
2598                         (void) printf("    %*s: object %llu, %llu blkptrs, "
2599                             "%llu freed, %s\n",
2600                             indent * 8, name,
2601                             (u_longlong_t)bpo->bpo_object,
2602                             (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2603                             (u_longlong_t)bpo->bpo_phys->bpo_num_freed,
2604                             bytes);
2605                 } else {
2606                         (void) printf("    %*s: object %llu, %llu blkptrs, "
2607                             "%s\n",
2608                             indent * 8, name,
2609                             (u_longlong_t)bpo->bpo_object,
2610                             (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2611                             bytes);
2612                 }
2613         }
2614
2615         if (dump_opt['d'] < 5)
2616                 return;
2617
2618
2619         if (indent == 0) {
2620                 (void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
2621                 (void) printf("\n");
2622         }
2623 }
2624
2625 static int
2626 dump_bookmark(dsl_pool_t *dp, char *name, boolean_t print_redact,
2627     boolean_t print_list)
2628 {
2629         int err = 0;
2630         zfs_bookmark_phys_t prop;
2631         objset_t *mos = dp->dp_spa->spa_meta_objset;
2632         err = dsl_bookmark_lookup(dp, name, NULL, &prop);
2633
2634         if (err != 0) {
2635                 return (err);
2636         }
2637
2638         (void) printf("\t#%s: ", strchr(name, '#') + 1);
2639         (void) printf("{guid: %llx creation_txg: %llu creation_time: "
2640             "%llu redaction_obj: %llu}\n", (u_longlong_t)prop.zbm_guid,
2641             (u_longlong_t)prop.zbm_creation_txg,
2642             (u_longlong_t)prop.zbm_creation_time,
2643             (u_longlong_t)prop.zbm_redaction_obj);
2644
2645         IMPLY(print_list, print_redact);
2646         if (!print_redact || prop.zbm_redaction_obj == 0)
2647                 return (0);
2648
2649         redaction_list_t *rl;
2650         VERIFY0(dsl_redaction_list_hold_obj(dp,
2651             prop.zbm_redaction_obj, FTAG, &rl));
2652
2653         redaction_list_phys_t *rlp = rl->rl_phys;
2654         (void) printf("\tRedacted:\n\t\tProgress: ");
2655         if (rlp->rlp_last_object != UINT64_MAX ||
2656             rlp->rlp_last_blkid != UINT64_MAX) {
2657                 (void) printf("%llu %llu (incomplete)\n",
2658                     (u_longlong_t)rlp->rlp_last_object,
2659                     (u_longlong_t)rlp->rlp_last_blkid);
2660         } else {
2661                 (void) printf("complete\n");
2662         }
2663         (void) printf("\t\tSnapshots: [");
2664         for (unsigned int i = 0; i < rlp->rlp_num_snaps; i++) {
2665                 if (i > 0)
2666                         (void) printf(", ");
2667                 (void) printf("%0llu",
2668                     (u_longlong_t)rlp->rlp_snaps[i]);
2669         }
2670         (void) printf("]\n\t\tLength: %llu\n",
2671             (u_longlong_t)rlp->rlp_num_entries);
2672
2673         if (!print_list) {
2674                 dsl_redaction_list_rele(rl, FTAG);
2675                 return (0);
2676         }
2677
2678         if (rlp->rlp_num_entries == 0) {
2679                 dsl_redaction_list_rele(rl, FTAG);
2680                 (void) printf("\t\tRedaction List: []\n\n");
2681                 return (0);
2682         }
2683
2684         redact_block_phys_t *rbp_buf;
2685         uint64_t size;
2686         dmu_object_info_t doi;
2687
2688         VERIFY0(dmu_object_info(mos, prop.zbm_redaction_obj, &doi));
2689         size = doi.doi_max_offset;
2690         rbp_buf = kmem_alloc(size, KM_SLEEP);
2691
2692         err = dmu_read(mos, prop.zbm_redaction_obj, 0, size,
2693             rbp_buf, 0);
2694         if (err != 0) {
2695                 dsl_redaction_list_rele(rl, FTAG);
2696                 kmem_free(rbp_buf, size);
2697                 return (err);
2698         }
2699
2700         (void) printf("\t\tRedaction List: [{object: %llx, offset: "
2701             "%llx, blksz: %x, count: %llx}",
2702             (u_longlong_t)rbp_buf[0].rbp_object,
2703             (u_longlong_t)rbp_buf[0].rbp_blkid,
2704             (uint_t)(redact_block_get_size(&rbp_buf[0])),
2705             (u_longlong_t)redact_block_get_count(&rbp_buf[0]));
2706
2707         for (size_t i = 1; i < rlp->rlp_num_entries; i++) {
2708                 (void) printf(",\n\t\t{object: %llx, offset: %llx, "
2709                     "blksz: %x, count: %llx}",
2710                     (u_longlong_t)rbp_buf[i].rbp_object,
2711                     (u_longlong_t)rbp_buf[i].rbp_blkid,
2712                     (uint_t)(redact_block_get_size(&rbp_buf[i])),
2713                     (u_longlong_t)redact_block_get_count(&rbp_buf[i]));
2714         }
2715         dsl_redaction_list_rele(rl, FTAG);
2716         kmem_free(rbp_buf, size);
2717         (void) printf("]\n\n");
2718         return (0);
2719 }
2720
2721 static void
2722 dump_bookmarks(objset_t *os, int verbosity)
2723 {
2724         zap_cursor_t zc;
2725         zap_attribute_t attr;
2726         dsl_dataset_t *ds = dmu_objset_ds(os);
2727         dsl_pool_t *dp = spa_get_dsl(os->os_spa);
2728         objset_t *mos = os->os_spa->spa_meta_objset;
2729         if (verbosity < 4)
2730                 return;
2731         dsl_pool_config_enter(dp, FTAG);
2732
2733         for (zap_cursor_init(&zc, mos, ds->ds_bookmarks_obj);
2734             zap_cursor_retrieve(&zc, &attr) == 0;
2735             zap_cursor_advance(&zc)) {
2736                 char osname[ZFS_MAX_DATASET_NAME_LEN];
2737                 char buf[ZFS_MAX_DATASET_NAME_LEN];
2738                 dmu_objset_name(os, osname);
2739                 VERIFY3S(0, <=, snprintf(buf, sizeof (buf), "%s#%s", osname,
2740                     attr.za_name));
2741                 (void) dump_bookmark(dp, buf, verbosity >= 5, verbosity >= 6);
2742         }
2743         zap_cursor_fini(&zc);
2744         dsl_pool_config_exit(dp, FTAG);
2745 }
2746
2747 static void
2748 bpobj_count_refd(bpobj_t *bpo)
2749 {
2750         mos_obj_refd(bpo->bpo_object);
2751
2752         if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
2753                 mos_obj_refd(bpo->bpo_phys->bpo_subobjs);
2754                 for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
2755                         uint64_t subobj;
2756                         bpobj_t subbpo;
2757                         int error;
2758                         VERIFY0(dmu_read(bpo->bpo_os,
2759                             bpo->bpo_phys->bpo_subobjs,
2760                             i * sizeof (subobj), sizeof (subobj), &subobj, 0));
2761                         error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
2762                         if (error != 0) {
2763                                 (void) printf("ERROR %u while trying to open "
2764                                     "subobj id %llu\n",
2765                                     error, (u_longlong_t)subobj);
2766                                 continue;
2767                         }
2768                         bpobj_count_refd(&subbpo);
2769                         bpobj_close(&subbpo);
2770                 }
2771         }
2772 }
2773
2774 static int
2775 dsl_deadlist_entry_count_refd(void *arg, dsl_deadlist_entry_t *dle)
2776 {
2777         spa_t *spa = arg;
2778         uint64_t empty_bpobj = spa->spa_dsl_pool->dp_empty_bpobj;
2779         if (dle->dle_bpobj.bpo_object != empty_bpobj)
2780                 bpobj_count_refd(&dle->dle_bpobj);
2781         return (0);
2782 }
2783
2784 static int
2785 dsl_deadlist_entry_dump(void *arg, dsl_deadlist_entry_t *dle)
2786 {
2787         ASSERT(arg == NULL);
2788         if (dump_opt['d'] >= 5) {
2789                 char buf[128];
2790                 (void) snprintf(buf, sizeof (buf),
2791                     "mintxg %llu -> obj %llu",
2792                     (longlong_t)dle->dle_mintxg,
2793                     (longlong_t)dle->dle_bpobj.bpo_object);
2794
2795                 dump_full_bpobj(&dle->dle_bpobj, buf, 0);
2796         } else {
2797                 (void) printf("mintxg %llu -> obj %llu\n",
2798                     (longlong_t)dle->dle_mintxg,
2799                     (longlong_t)dle->dle_bpobj.bpo_object);
2800         }
2801         return (0);
2802 }
2803
2804 static void
2805 dump_blkptr_list(dsl_deadlist_t *dl, char *name)
2806 {
2807         char bytes[32];
2808         char comp[32];
2809         char uncomp[32];
2810         char entries[32];
2811         spa_t *spa = dmu_objset_spa(dl->dl_os);
2812         uint64_t empty_bpobj = spa->spa_dsl_pool->dp_empty_bpobj;
2813
2814         if (dl->dl_oldfmt) {
2815                 if (dl->dl_bpobj.bpo_object != empty_bpobj)
2816                         bpobj_count_refd(&dl->dl_bpobj);
2817         } else {
2818                 mos_obj_refd(dl->dl_object);
2819                 dsl_deadlist_iterate(dl, dsl_deadlist_entry_count_refd, spa);
2820         }
2821
2822         /* make sure nicenum has enough space */
2823         CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
2824         CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
2825         CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
2826         CTASSERT(sizeof (entries) >= NN_NUMBUF_SZ);
2827
2828         if (dump_opt['d'] < 3)
2829                 return;
2830
2831         if (dl->dl_oldfmt) {
2832                 dump_full_bpobj(&dl->dl_bpobj, "old-format deadlist", 0);
2833                 return;
2834         }
2835
2836         zdb_nicenum(dl->dl_phys->dl_used, bytes, sizeof (bytes));
2837         zdb_nicenum(dl->dl_phys->dl_comp, comp, sizeof (comp));
2838         zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp, sizeof (uncomp));
2839         zdb_nicenum(avl_numnodes(&dl->dl_tree), entries, sizeof (entries));
2840         (void) printf("\n    %s: %s (%s/%s comp), %s entries\n",
2841             name, bytes, comp, uncomp, entries);
2842
2843         if (dump_opt['d'] < 4)
2844                 return;
2845
2846         (void) printf("\n");
2847
2848         dsl_deadlist_iterate(dl, dsl_deadlist_entry_dump, NULL);
2849 }
2850
2851 static int
2852 verify_dd_livelist(objset_t *os)
2853 {
2854         uint64_t ll_used, used, ll_comp, comp, ll_uncomp, uncomp;
2855         dsl_pool_t *dp = spa_get_dsl(os->os_spa);
2856         dsl_dir_t  *dd = os->os_dsl_dataset->ds_dir;
2857
2858         ASSERT(!dmu_objset_is_snapshot(os));
2859         if (!dsl_deadlist_is_open(&dd->dd_livelist))
2860                 return (0);
2861
2862         /* Iterate through the livelist to check for duplicates */
2863         dsl_deadlist_iterate(&dd->dd_livelist, sublivelist_verify_lightweight,
2864             NULL);
2865
2866         dsl_pool_config_enter(dp, FTAG);
2867         dsl_deadlist_space(&dd->dd_livelist, &ll_used,
2868             &ll_comp, &ll_uncomp);
2869
2870         dsl_dataset_t *origin_ds;
2871         ASSERT(dsl_pool_config_held(dp));
2872         VERIFY0(dsl_dataset_hold_obj(dp,
2873             dsl_dir_phys(dd)->dd_origin_obj, FTAG, &origin_ds));
2874         VERIFY0(dsl_dataset_space_written(origin_ds, os->os_dsl_dataset,
2875             &used, &comp, &uncomp));
2876         dsl_dataset_rele(origin_ds, FTAG);
2877         dsl_pool_config_exit(dp, FTAG);
2878         /*
2879          *  It's possible that the dataset's uncomp space is larger than the
2880          *  livelist's because livelists do not track embedded block pointers
2881          */
2882         if (used != ll_used || comp != ll_comp || uncomp < ll_uncomp) {
2883                 char nice_used[32], nice_comp[32], nice_uncomp[32];
2884                 (void) printf("Discrepancy in space accounting:\n");
2885                 zdb_nicenum(used, nice_used, sizeof (nice_used));
2886                 zdb_nicenum(comp, nice_comp, sizeof (nice_comp));
2887                 zdb_nicenum(uncomp, nice_uncomp, sizeof (nice_uncomp));
2888                 (void) printf("dir: used %s, comp %s, uncomp %s\n",
2889                     nice_used, nice_comp, nice_uncomp);
2890                 zdb_nicenum(ll_used, nice_used, sizeof (nice_used));
2891                 zdb_nicenum(ll_comp, nice_comp, sizeof (nice_comp));
2892                 zdb_nicenum(ll_uncomp, nice_uncomp, sizeof (nice_uncomp));
2893                 (void) printf("livelist: used %s, comp %s, uncomp %s\n",
2894                     nice_used, nice_comp, nice_uncomp);
2895                 return (1);
2896         }
2897         return (0);
2898 }
2899
2900 static avl_tree_t idx_tree;
2901 static avl_tree_t domain_tree;
2902 static boolean_t fuid_table_loaded;
2903 static objset_t *sa_os = NULL;
2904 static sa_attr_type_t *sa_attr_table = NULL;
2905
2906 static int
2907 open_objset(const char *path, void *tag, objset_t **osp)
2908 {
2909         int err;
2910         uint64_t sa_attrs = 0;
2911         uint64_t version = 0;
2912
2913         VERIFY3P(sa_os, ==, NULL);
2914         /*
2915          * We can't own an objset if it's redacted.  Therefore, we do this
2916          * dance: hold the objset, then acquire a long hold on its dataset, then
2917          * release the pool (which is held as part of holding the objset).
2918          */
2919         err = dmu_objset_hold(path, tag, osp);
2920         if (err != 0) {
2921                 (void) fprintf(stderr, "failed to hold dataset '%s': %s\n",
2922                     path, strerror(err));
2923                 return (err);
2924         }
2925         dsl_dataset_long_hold(dmu_objset_ds(*osp), tag);
2926         dsl_pool_rele(dmu_objset_pool(*osp), tag);
2927
2928         if (dmu_objset_type(*osp) == DMU_OST_ZFS && !(*osp)->os_encrypted) {
2929                 (void) zap_lookup(*osp, MASTER_NODE_OBJ, ZPL_VERSION_STR,
2930                     8, 1, &version);
2931                 if (version >= ZPL_VERSION_SA) {
2932                         (void) zap_lookup(*osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
2933                             8, 1, &sa_attrs);
2934                 }
2935                 err = sa_setup(*osp, sa_attrs, zfs_attr_table, ZPL_END,
2936                     &sa_attr_table);
2937                 if (err != 0) {
2938                         (void) fprintf(stderr, "sa_setup failed: %s\n",
2939                             strerror(err));
2940                         dsl_dataset_long_rele(dmu_objset_ds(*osp), tag);
2941                         dsl_dataset_rele(dmu_objset_ds(*osp), tag);
2942                         *osp = NULL;
2943                 }
2944         }
2945         sa_os = *osp;
2946
2947         return (0);
2948 }
2949
2950 static void
2951 close_objset(objset_t *os, void *tag)
2952 {
2953         VERIFY3P(os, ==, sa_os);
2954         if (os->os_sa != NULL)
2955                 sa_tear_down(os);
2956         dsl_dataset_long_rele(dmu_objset_ds(os), tag);
2957         dsl_dataset_rele(dmu_objset_ds(os), tag);
2958         sa_attr_table = NULL;
2959         sa_os = NULL;
2960 }
2961
2962 static void
2963 fuid_table_destroy(void)
2964 {
2965         if (fuid_table_loaded) {
2966                 zfs_fuid_table_destroy(&idx_tree, &domain_tree);
2967                 fuid_table_loaded = B_FALSE;
2968         }
2969 }
2970
2971 /*
2972  * print uid or gid information.
2973  * For normal POSIX id just the id is printed in decimal format.
2974  * For CIFS files with FUID the fuid is printed in hex followed by
2975  * the domain-rid string.
2976  */
2977 static void
2978 print_idstr(uint64_t id, const char *id_type)
2979 {
2980         if (FUID_INDEX(id)) {
2981                 char *domain;
2982
2983                 domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
2984                 (void) printf("\t%s     %llx [%s-%d]\n", id_type,
2985                     (u_longlong_t)id, domain, (int)FUID_RID(id));
2986         } else {
2987                 (void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
2988         }
2989
2990 }
2991
2992 static void
2993 dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
2994 {
2995         uint32_t uid_idx, gid_idx;
2996
2997         uid_idx = FUID_INDEX(uid);
2998         gid_idx = FUID_INDEX(gid);
2999
3000         /* Load domain table, if not already loaded */
3001         if (!fuid_table_loaded && (uid_idx || gid_idx)) {
3002                 uint64_t fuid_obj;
3003
3004                 /* first find the fuid object.  It lives in the master node */
3005                 VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
3006                     8, 1, &fuid_obj) == 0);
3007                 zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
3008                 (void) zfs_fuid_table_load(os, fuid_obj,
3009                     &idx_tree, &domain_tree);
3010                 fuid_table_loaded = B_TRUE;
3011         }
3012
3013         print_idstr(uid, "uid");
3014         print_idstr(gid, "gid");
3015 }
3016
3017 static void
3018 dump_znode_sa_xattr(sa_handle_t *hdl)
3019 {
3020         nvlist_t *sa_xattr;
3021         nvpair_t *elem = NULL;
3022         int sa_xattr_size = 0;
3023         int sa_xattr_entries = 0;
3024         int error;
3025         char *sa_xattr_packed;
3026
3027         error = sa_size(hdl, sa_attr_table[ZPL_DXATTR], &sa_xattr_size);
3028         if (error || sa_xattr_size == 0)
3029                 return;
3030
3031         sa_xattr_packed = malloc(sa_xattr_size);
3032         if (sa_xattr_packed == NULL)
3033                 return;
3034
3035         error = sa_lookup(hdl, sa_attr_table[ZPL_DXATTR],
3036             sa_xattr_packed, sa_xattr_size);
3037         if (error) {
3038                 free(sa_xattr_packed);
3039                 return;
3040         }
3041
3042         error = nvlist_unpack(sa_xattr_packed, sa_xattr_size, &sa_xattr, 0);
3043         if (error) {
3044                 free(sa_xattr_packed);
3045                 return;
3046         }
3047
3048         while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL)
3049                 sa_xattr_entries++;
3050
3051         (void) printf("\tSA xattrs: %d bytes, %d entries\n\n",
3052             sa_xattr_size, sa_xattr_entries);
3053         while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL) {
3054                 uchar_t *value;
3055                 uint_t cnt, idx;
3056
3057                 (void) printf("\t\t%s = ", nvpair_name(elem));
3058                 nvpair_value_byte_array(elem, &value, &cnt);
3059                 for (idx = 0; idx < cnt; ++idx) {
3060                         if (isprint(value[idx]))
3061                                 (void) putchar(value[idx]);
3062                         else
3063                                 (void) printf("\\%3.3o", value[idx]);
3064                 }
3065                 (void) putchar('\n');
3066         }
3067
3068         nvlist_free(sa_xattr);
3069         free(sa_xattr_packed);
3070 }
3071
3072 static void
3073 dump_znode_symlink(sa_handle_t *hdl)
3074 {
3075         int sa_symlink_size = 0;
3076         char linktarget[MAXPATHLEN];
3077         linktarget[0] = '\0';
3078         int error;
3079
3080         error = sa_size(hdl, sa_attr_table[ZPL_SYMLINK], &sa_symlink_size);
3081         if (error || sa_symlink_size == 0) {
3082                 return;
3083         }
3084         if (sa_lookup(hdl, sa_attr_table[ZPL_SYMLINK],
3085             &linktarget, sa_symlink_size) == 0)
3086                 (void) printf("\ttarget %s\n", linktarget);
3087 }
3088
3089 /*ARGSUSED*/
3090 static void
3091 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
3092 {
3093         char path[MAXPATHLEN * 2];      /* allow for xattr and failure prefix */
3094         sa_handle_t *hdl;
3095         uint64_t xattr, rdev, gen;
3096         uint64_t uid, gid, mode, fsize, parent, links;
3097         uint64_t pflags;
3098         uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
3099         time_t z_crtime, z_atime, z_mtime, z_ctime;
3100         sa_bulk_attr_t bulk[12];
3101         int idx = 0;
3102         int error;
3103
3104         VERIFY3P(os, ==, sa_os);
3105         if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
3106                 (void) printf("Failed to get handle for SA znode\n");
3107                 return;
3108         }
3109
3110         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
3111         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
3112         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
3113             &links, 8);
3114         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
3115         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
3116             &mode, 8);
3117         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
3118             NULL, &parent, 8);
3119         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
3120             &fsize, 8);
3121         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
3122             acctm, 16);
3123         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
3124             modtm, 16);
3125         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
3126             crtm, 16);
3127         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
3128             chgtm, 16);
3129         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
3130             &pflags, 8);
3131
3132         if (sa_bulk_lookup(hdl, bulk, idx)) {
3133                 (void) sa_handle_destroy(hdl);
3134                 return;
3135         }
3136
3137         z_crtime = (time_t)crtm[0];
3138         z_atime = (time_t)acctm[0];
3139         z_mtime = (time_t)modtm[0];
3140         z_ctime = (time_t)chgtm[0];
3141
3142         if (dump_opt['d'] > 4) {
3143                 error = zfs_obj_to_path(os, object, path, sizeof (path));
3144                 if (error == ESTALE) {
3145                         (void) snprintf(path, sizeof (path), "on delete queue");
3146                 } else if (error != 0) {
3147                         leaked_objects++;
3148                         (void) snprintf(path, sizeof (path),
3149                             "path not found, possibly leaked");
3150                 }
3151                 (void) printf("\tpath   %s\n", path);
3152         }
3153
3154         if (S_ISLNK(mode))
3155                 dump_znode_symlink(hdl);
3156         dump_uidgid(os, uid, gid);
3157         (void) printf("\tatime  %s", ctime(&z_atime));
3158         (void) printf("\tmtime  %s", ctime(&z_mtime));
3159         (void) printf("\tctime  %s", ctime(&z_ctime));
3160         (void) printf("\tcrtime %s", ctime(&z_crtime));
3161         (void) printf("\tgen    %llu\n", (u_longlong_t)gen);
3162         (void) printf("\tmode   %llo\n", (u_longlong_t)mode);
3163         (void) printf("\tsize   %llu\n", (u_longlong_t)fsize);
3164         (void) printf("\tparent %llu\n", (u_longlong_t)parent);
3165         (void) printf("\tlinks  %llu\n", (u_longlong_t)links);
3166         (void) printf("\tpflags %llx\n", (u_longlong_t)pflags);
3167         if (dmu_objset_projectquota_enabled(os) && (pflags & ZFS_PROJID)) {
3168                 uint64_t projid;
3169
3170                 if (sa_lookup(hdl, sa_attr_table[ZPL_PROJID], &projid,
3171                     sizeof (uint64_t)) == 0)
3172                         (void) printf("\tprojid %llu\n", (u_longlong_t)projid);
3173         }
3174         if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
3175             sizeof (uint64_t)) == 0)
3176                 (void) printf("\txattr  %llu\n", (u_longlong_t)xattr);
3177         if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
3178             sizeof (uint64_t)) == 0)
3179                 (void) printf("\trdev   0x%016llx\n", (u_longlong_t)rdev);
3180         dump_znode_sa_xattr(hdl);
3181         sa_handle_destroy(hdl);
3182 }
3183
3184 /*ARGSUSED*/
3185 static void
3186 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
3187 {
3188 }
3189
3190 /*ARGSUSED*/
3191 static void
3192 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
3193 {
3194 }
3195
3196 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
3197         dump_none,              /* unallocated                  */
3198         dump_zap,               /* object directory             */
3199         dump_uint64,            /* object array                 */
3200         dump_none,              /* packed nvlist                */
3201         dump_packed_nvlist,     /* packed nvlist size           */
3202         dump_none,              /* bpobj                        */
3203         dump_bpobj,             /* bpobj header                 */
3204         dump_none,              /* SPA space map header         */
3205         dump_none,              /* SPA space map                */
3206         dump_none,              /* ZIL intent log               */
3207         dump_dnode,             /* DMU dnode                    */
3208         dump_dmu_objset,        /* DMU objset                   */
3209         dump_dsl_dir,           /* DSL directory                */
3210         dump_zap,               /* DSL directory child map      */
3211         dump_zap,               /* DSL dataset snap map         */
3212         dump_zap,               /* DSL props                    */
3213         dump_dsl_dataset,       /* DSL dataset                  */
3214         dump_znode,             /* ZFS znode                    */
3215         dump_acl,               /* ZFS V0 ACL                   */
3216         dump_uint8,             /* ZFS plain file               */
3217         dump_zpldir,            /* ZFS directory                */
3218         dump_zap,               /* ZFS master node              */
3219         dump_zap,               /* ZFS delete queue             */
3220         dump_uint8,             /* zvol object                  */
3221         dump_zap,               /* zvol prop                    */
3222         dump_uint8,             /* other uint8[]                */
3223         dump_uint64,            /* other uint64[]               */
3224         dump_zap,               /* other ZAP                    */
3225         dump_zap,               /* persistent error log         */
3226         dump_uint8,             /* SPA history                  */
3227         dump_history_offsets,   /* SPA history offsets          */
3228         dump_zap,               /* Pool properties              */
3229         dump_zap,               /* DSL permissions              */
3230         dump_acl,               /* ZFS ACL                      */
3231         dump_uint8,             /* ZFS SYSACL                   */
3232         dump_none,              /* FUID nvlist                  */
3233         dump_packed_nvlist,     /* FUID nvlist size             */
3234         dump_zap,               /* DSL dataset next clones      */
3235         dump_zap,               /* DSL scrub queue              */
3236         dump_zap,               /* ZFS user/group/project used  */
3237         dump_zap,               /* ZFS user/group/project quota */
3238         dump_zap,               /* snapshot refcount tags       */
3239         dump_ddt_zap,           /* DDT ZAP object               */
3240         dump_zap,               /* DDT statistics               */
3241         dump_znode,             /* SA object                    */
3242         dump_zap,               /* SA Master Node               */
3243         dump_sa_attrs,          /* SA attribute registration    */
3244         dump_sa_layouts,        /* SA attribute layouts         */
3245         dump_zap,               /* DSL scrub translations       */
3246         dump_none,              /* fake dedup BP                */
3247         dump_zap,               /* deadlist                     */
3248         dump_none,              /* deadlist hdr                 */
3249         dump_zap,               /* dsl clones                   */
3250         dump_bpobj_subobjs,     /* bpobj subobjs                */
3251         dump_unknown,           /* Unknown type, must be last   */
3252 };
3253
3254 static boolean_t
3255 match_object_type(dmu_object_type_t obj_type, uint64_t flags)
3256 {
3257         boolean_t match = B_TRUE;
3258
3259         switch (obj_type) {
3260         case DMU_OT_DIRECTORY_CONTENTS:
3261                 if (!(flags & ZOR_FLAG_DIRECTORY))
3262                         match = B_FALSE;
3263                 break;
3264         case DMU_OT_PLAIN_FILE_CONTENTS:
3265                 if (!(flags & ZOR_FLAG_PLAIN_FILE))
3266                         match = B_FALSE;
3267                 break;
3268         case DMU_OT_SPACE_MAP:
3269                 if (!(flags & ZOR_FLAG_SPACE_MAP))
3270                         match = B_FALSE;
3271                 break;
3272         default:
3273                 if (strcmp(zdb_ot_name(obj_type), "zap") == 0) {
3274                         if (!(flags & ZOR_FLAG_ZAP))
3275                                 match = B_FALSE;
3276                         break;
3277                 }
3278
3279                 /*
3280                  * If all bits except some of the supported flags are
3281                  * set, the user combined the all-types flag (A) with
3282                  * a negated flag to exclude some types (e.g. A-f to
3283                  * show all object types except plain files).
3284                  */
3285                 if ((flags | ZOR_SUPPORTED_FLAGS) != ZOR_FLAG_ALL_TYPES)
3286                         match = B_FALSE;
3287
3288                 break;
3289         }
3290
3291         return (match);
3292 }
3293
3294 static void
3295 dump_object(objset_t *os, uint64_t object, int verbosity,
3296     boolean_t *print_header, uint64_t *dnode_slots_used, uint64_t flags)
3297 {
3298         dmu_buf_t *db = NULL;
3299         dmu_object_info_t doi;
3300         dnode_t *dn;
3301         boolean_t dnode_held = B_FALSE;
3302         void *bonus = NULL;
3303         size_t bsize = 0;
3304         char iblk[32], dblk[32], lsize[32], asize[32], fill[32], dnsize[32];
3305         char bonus_size[32];
3306         char aux[50];
3307         int error;
3308
3309         /* make sure nicenum has enough space */
3310         CTASSERT(sizeof (iblk) >= NN_NUMBUF_SZ);
3311         CTASSERT(sizeof (dblk) >= NN_NUMBUF_SZ);
3312         CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
3313         CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
3314         CTASSERT(sizeof (bonus_size) >= NN_NUMBUF_SZ);
3315
3316         if (*print_header) {
3317                 (void) printf("\n%10s  %3s  %5s  %5s  %5s  %6s  %5s  %6s  %s\n",
3318                     "Object", "lvl", "iblk", "dblk", "dsize", "dnsize",
3319                     "lsize", "%full", "type");
3320                 *print_header = 0;
3321         }
3322
3323         if (object == 0) {
3324                 dn = DMU_META_DNODE(os);
3325                 dmu_object_info_from_dnode(dn, &doi);
3326         } else {
3327                 /*
3328                  * Encrypted datasets will have sensitive bonus buffers
3329                  * encrypted. Therefore we cannot hold the bonus buffer and
3330                  * must hold the dnode itself instead.
3331                  */
3332                 error = dmu_object_info(os, object, &doi);
3333                 if (error)
3334                         fatal("dmu_object_info() failed, errno %u", error);
3335
3336                 if (os->os_encrypted &&
3337                     DMU_OT_IS_ENCRYPTED(doi.doi_bonus_type)) {
3338                         error = dnode_hold(os, object, FTAG, &dn);
3339                         if (error)
3340                                 fatal("dnode_hold() failed, errno %u", error);
3341                         dnode_held = B_TRUE;
3342                 } else {
3343                         error = dmu_bonus_hold(os, object, FTAG, &db);
3344                         if (error)
3345                                 fatal("dmu_bonus_hold(%llu) failed, errno %u",
3346                                     object, error);
3347                         bonus = db->db_data;
3348                         bsize = db->db_size;
3349                         dn = DB_DNODE((dmu_buf_impl_t *)db);
3350                 }
3351         }
3352
3353         /*
3354          * Default to showing all object types if no flags were specified.
3355          */
3356         if (flags != 0 && flags != ZOR_FLAG_ALL_TYPES &&
3357             !match_object_type(doi.doi_type, flags))
3358                 goto out;
3359
3360         if (dnode_slots_used)
3361                 *dnode_slots_used = doi.doi_dnodesize / DNODE_MIN_SIZE;
3362
3363         zdb_nicenum(doi.doi_metadata_block_size, iblk, sizeof (iblk));
3364         zdb_nicenum(doi.doi_data_block_size, dblk, sizeof (dblk));
3365         zdb_nicenum(doi.doi_max_offset, lsize, sizeof (lsize));
3366         zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize, sizeof (asize));
3367         zdb_nicenum(doi.doi_bonus_size, bonus_size, sizeof (bonus_size));
3368         zdb_nicenum(doi.doi_dnodesize, dnsize, sizeof (dnsize));
3369         (void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
3370             doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
3371             doi.doi_max_offset);
3372
3373         aux[0] = '\0';
3374
3375         if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
3376                 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
3377                     " (K=%s)", ZDB_CHECKSUM_NAME(doi.doi_checksum));
3378         }
3379
3380         if (doi.doi_compress == ZIO_COMPRESS_INHERIT &&
3381             ZIO_COMPRESS_HASLEVEL(os->os_compress) && verbosity >= 6) {
3382                 const char *compname = NULL;
3383                 if (zfs_prop_index_to_string(ZFS_PROP_COMPRESSION,
3384                     ZIO_COMPRESS_RAW(os->os_compress, os->os_complevel),
3385                     &compname) == 0) {
3386                         (void) snprintf(aux + strlen(aux),
3387                             sizeof (aux) - strlen(aux), " (Z=inherit=%s)",
3388                             compname);
3389                 } else {
3390                         (void) snprintf(aux + strlen(aux),
3391                             sizeof (aux) - strlen(aux),
3392                             " (Z=inherit=%s-unknown)",
3393                             ZDB_COMPRESS_NAME(os->os_compress));
3394                 }
3395         } else if (doi.doi_compress == ZIO_COMPRESS_INHERIT && verbosity >= 6) {
3396                 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
3397                     " (Z=inherit=%s)", ZDB_COMPRESS_NAME(os->os_compress));
3398         } else if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
3399                 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
3400                     " (Z=%s)", ZDB_COMPRESS_NAME(doi.doi_compress));
3401         }
3402
3403         (void) printf("%10lld  %3u  %5s  %5s  %5s  %6s  %5s  %6s  %s%s\n",
3404             (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
3405             asize, dnsize, lsize, fill, zdb_ot_name(doi.doi_type), aux);
3406
3407         if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
3408                 (void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %5s  %6s  %s\n",
3409                     "", "", "", "", "", "", bonus_size, "bonus",
3410                     zdb_ot_name(doi.doi_bonus_type));
3411         }
3412
3413         if (verbosity >= 4) {
3414                 (void) printf("\tdnode flags: %s%s%s%s\n",
3415                     (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
3416                     "USED_BYTES " : "",
3417                     (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
3418                     "USERUSED_ACCOUNTED " : "",
3419                     (dn->dn_phys->dn_flags & DNODE_FLAG_USEROBJUSED_ACCOUNTED) ?
3420                     "USEROBJUSED_ACCOUNTED " : "",
3421                     (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
3422                     "SPILL_BLKPTR" : "");
3423                 (void) printf("\tdnode maxblkid: %llu\n",
3424                     (longlong_t)dn->dn_phys->dn_maxblkid);
3425
3426                 if (!dnode_held) {
3427                         object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os,
3428                             object, bonus, bsize);
3429                 } else {
3430                         (void) printf("\t\t(bonus encrypted)\n");
3431                 }
3432
3433                 if (!os->os_encrypted || !DMU_OT_IS_ENCRYPTED(doi.doi_type)) {
3434                         object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object,
3435                             NULL, 0);
3436                 } else {
3437                         (void) printf("\t\t(object encrypted)\n");
3438                 }
3439
3440                 *print_header = B_TRUE;
3441         }
3442
3443         if (verbosity >= 5)
3444                 dump_indirect(dn);
3445
3446         if (verbosity >= 5) {
3447                 /*
3448                  * Report the list of segments that comprise the object.
3449                  */
3450                 uint64_t start = 0;
3451                 uint64_t end;
3452                 uint64_t blkfill = 1;
3453                 int minlvl = 1;
3454
3455                 if (dn->dn_type == DMU_OT_DNODE) {
3456                         minlvl = 0;
3457                         blkfill = DNODES_PER_BLOCK;
3458                 }
3459
3460                 for (;;) {
3461                         char segsize[32];
3462                         /* make sure nicenum has enough space */
3463                         CTASSERT(sizeof (segsize) >= NN_NUMBUF_SZ);
3464                         error = dnode_next_offset(dn,
3465                             0, &start, minlvl, blkfill, 0);
3466                         if (error)
3467                                 break;
3468                         end = start;
3469                         error = dnode_next_offset(dn,
3470                             DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
3471                         zdb_nicenum(end - start, segsize, sizeof (segsize));
3472                         (void) printf("\t\tsegment [%016llx, %016llx)"
3473                             " size %5s\n", (u_longlong_t)start,
3474                             (u_longlong_t)end, segsize);
3475                         if (error)
3476                                 break;
3477                         start = end;
3478                 }
3479         }
3480
3481 out:
3482         if (db != NULL)
3483                 dmu_buf_rele(db, FTAG);
3484         if (dnode_held)
3485                 dnode_rele(dn, FTAG);
3486 }
3487
3488 static void
3489 count_dir_mos_objects(dsl_dir_t *dd)
3490 {
3491         mos_obj_refd(dd->dd_object);
3492         mos_obj_refd(dsl_dir_phys(dd)->dd_child_dir_zapobj);
3493         mos_obj_refd(dsl_dir_phys(dd)->dd_deleg_zapobj);
3494         mos_obj_refd(dsl_dir_phys(dd)->dd_props_zapobj);
3495         mos_obj_refd(dsl_dir_phys(dd)->dd_clones);
3496
3497         /*
3498          * The dd_crypto_obj can be referenced by multiple dsl_dir's.
3499          * Ignore the references after the first one.
3500          */
3501         mos_obj_refd_multiple(dd->dd_crypto_obj);
3502 }
3503
3504 static void
3505 count_ds_mos_objects(dsl_dataset_t *ds)
3506 {
3507         mos_obj_refd(ds->ds_object);
3508         mos_obj_refd(dsl_dataset_phys(ds)->ds_next_clones_obj);
3509         mos_obj_refd(dsl_dataset_phys(ds)->ds_props_obj);
3510         mos_obj_refd(dsl_dataset_phys(ds)->ds_userrefs_obj);
3511         mos_obj_refd(dsl_dataset_phys(ds)->ds_snapnames_zapobj);
3512         mos_obj_refd(ds->ds_bookmarks_obj);
3513
3514         if (!dsl_dataset_is_snapshot(ds)) {
3515                 count_dir_mos_objects(ds->ds_dir);
3516         }
3517 }
3518
3519 static const char *objset_types[DMU_OST_NUMTYPES] = {
3520         "NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
3521
3522 /*
3523  * Parse a string denoting a range of object IDs of the form
3524  * <start>[:<end>[:flags]], and store the results in zor.
3525  * Return 0 on success. On error, return 1 and update the msg
3526  * pointer to point to a descriptive error message.
3527  */
3528 static int
3529 parse_object_range(char *range, zopt_object_range_t *zor, char **msg)
3530 {
3531         uint64_t flags = 0;
3532         char *p, *s, *dup, *flagstr;
3533         size_t len;
3534         int i;
3535         int rc = 0;
3536
3537         if (strchr(range, ':') == NULL) {
3538                 zor->zor_obj_start = strtoull(range, &p, 0);
3539                 if (*p != '\0') {
3540                         *msg = "Invalid characters in object ID";
3541                         rc = 1;
3542                 }
3543                 zor->zor_obj_end = zor->zor_obj_start;
3544                 return (rc);
3545         }
3546
3547         if (strchr(range, ':') == range) {
3548                 *msg = "Invalid leading colon";
3549                 rc = 1;
3550                 return (rc);
3551         }
3552
3553         len = strlen(range);
3554         if (range[len - 1] == ':') {
3555                 *msg = "Invalid trailing colon";
3556                 rc = 1;
3557                 return (rc);
3558         }
3559
3560         dup = strdup(range);
3561         s = strtok(dup, ":");
3562         zor->zor_obj_start = strtoull(s, &p, 0);
3563
3564         if (*p != '\0') {
3565                 *msg = "Invalid characters in start object ID";
3566                 rc = 1;
3567                 goto out;
3568         }
3569
3570         s = strtok(NULL, ":");
3571         zor->zor_obj_end = strtoull(s, &p, 0);
3572
3573         if (*p != '\0') {
3574                 *msg = "Invalid characters in end object ID";
3575                 rc = 1;
3576                 goto out;
3577         }
3578
3579         if (zor->zor_obj_start > zor->zor_obj_end) {
3580                 *msg = "Start object ID may not exceed end object ID";
3581                 rc = 1;
3582                 goto out;
3583         }
3584
3585         s = strtok(NULL, ":");
3586         if (s == NULL) {
3587                 zor->zor_flags = ZOR_FLAG_ALL_TYPES;
3588                 goto out;
3589         } else if (strtok(NULL, ":") != NULL) {
3590                 *msg = "Invalid colon-delimited field after flags";
3591                 rc = 1;
3592                 goto out;
3593         }
3594
3595         flagstr = s;
3596         for (i = 0; flagstr[i]; i++) {
3597                 int bit;
3598                 boolean_t negation = (flagstr[i] == '-');
3599
3600                 if (negation) {
3601                         i++;
3602                         if (flagstr[i] == '\0') {
3603                                 *msg = "Invalid trailing negation operator";
3604                                 rc = 1;
3605                                 goto out;
3606                         }
3607                 }
3608                 bit = flagbits[(uchar_t)flagstr[i]];
3609                 if (bit == 0) {
3610                         *msg = "Invalid flag";
3611                         rc = 1;
3612                         goto out;
3613                 }
3614                 if (negation)
3615                         flags &= ~bit;
3616                 else
3617                         flags |= bit;
3618         }
3619         zor->zor_flags = flags;
3620
3621 out:
3622         free(dup);
3623         return (rc);
3624 }
3625
3626 static void
3627 dump_objset(objset_t *os)
3628 {
3629         dmu_objset_stats_t dds = { 0 };
3630         uint64_t object, object_count;
3631         uint64_t refdbytes, usedobjs, scratch;
3632         char numbuf[32];
3633         char blkbuf[BP_SPRINTF_LEN + 20];
3634         char osname[ZFS_MAX_DATASET_NAME_LEN];
3635         const char *type = "UNKNOWN";
3636         int verbosity = dump_opt['d'];
3637         boolean_t print_header;
3638         unsigned i;
3639         int error;
3640         uint64_t total_slots_used = 0;
3641         uint64_t max_slot_used = 0;
3642         uint64_t dnode_slots;
3643         uint64_t obj_start;
3644         uint64_t obj_end;
3645         uint64_t flags;
3646
3647         /* make sure nicenum has enough space */
3648         CTASSERT(sizeof (numbuf) >= NN_NUMBUF_SZ);
3649
3650         dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
3651         dmu_objset_fast_stat(os, &dds);
3652         dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
3653
3654         print_header = B_TRUE;
3655
3656         if (dds.dds_type < DMU_OST_NUMTYPES)
3657                 type = objset_types[dds.dds_type];
3658
3659         if (dds.dds_type == DMU_OST_META) {
3660                 dds.dds_creation_txg = TXG_INITIAL;
3661                 usedobjs = BP_GET_FILL(os->os_rootbp);
3662                 refdbytes = dsl_dir_phys(os->os_spa->spa_dsl_pool->dp_mos_dir)->
3663                     dd_used_bytes;
3664         } else {
3665                 dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
3666         }
3667
3668         ASSERT3U(usedobjs, ==, BP_GET_FILL(os->os_rootbp));
3669
3670         zdb_nicenum(refdbytes, numbuf, sizeof (numbuf));
3671
3672         if (verbosity >= 4) {
3673                 (void) snprintf(blkbuf, sizeof (blkbuf), ", rootbp ");
3674                 (void) snprintf_blkptr(blkbuf + strlen(blkbuf),
3675                     sizeof (blkbuf) - strlen(blkbuf), os->os_rootbp);
3676         } else {
3677                 blkbuf[0] = '\0';
3678         }
3679
3680         dmu_objset_name(os, osname);
3681
3682         (void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
3683             "%s, %llu objects%s%s\n",
3684             osname, type, (u_longlong_t)dmu_objset_id(os),
3685             (u_longlong_t)dds.dds_creation_txg,
3686             numbuf, (u_longlong_t)usedobjs, blkbuf,
3687             (dds.dds_inconsistent) ? " (inconsistent)" : "");
3688
3689         for (i = 0; i < zopt_object_args; i++) {
3690                 obj_start = zopt_object_ranges[i].zor_obj_start;
3691                 obj_end = zopt_object_ranges[i].zor_obj_end;
3692                 flags = zopt_object_ranges[i].zor_flags;
3693
3694                 object = obj_start;
3695                 if (object == 0 || obj_start == obj_end)
3696                         dump_object(os, object, verbosity, &print_header, NULL,
3697                             flags);
3698                 else
3699                         object--;
3700
3701                 while ((dmu_object_next(os, &object, B_FALSE, 0) == 0) &&
3702                     object <= obj_end) {
3703                         dump_object(os, object, verbosity, &print_header, NULL,
3704                             flags);
3705                 }
3706         }
3707
3708         if (zopt_object_args > 0) {
3709                 (void) printf("\n");
3710                 return;
3711         }
3712
3713         if (dump_opt['i'] != 0 || verbosity >= 2)
3714                 dump_intent_log(dmu_objset_zil(os));
3715
3716         if (dmu_objset_ds(os) != NULL) {
3717                 dsl_dataset_t *ds = dmu_objset_ds(os);
3718                 dump_blkptr_list(&ds->ds_deadlist, "Deadlist");
3719                 if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist) &&
3720                     !dmu_objset_is_snapshot(os)) {
3721                         dump_blkptr_list(&ds->ds_dir->dd_livelist, "Livelist");
3722                         if (verify_dd_livelist(os) != 0)
3723                                 fatal("livelist is incorrect");
3724                 }
3725
3726                 if (dsl_dataset_remap_deadlist_exists(ds)) {
3727                         (void) printf("ds_remap_deadlist:\n");
3728                         dump_blkptr_list(&ds->ds_remap_deadlist, "Deadlist");
3729                 }
3730                 count_ds_mos_objects(ds);
3731         }
3732
3733         if (dmu_objset_ds(os) != NULL)
3734                 dump_bookmarks(os, verbosity);
3735
3736         if (verbosity < 2)
3737                 return;
3738
3739         if (BP_IS_HOLE(os->os_rootbp))
3740                 return;
3741
3742         dump_object(os, 0, verbosity, &print_header, NULL, 0);
3743         object_count = 0;
3744         if (DMU_USERUSED_DNODE(os) != NULL &&
3745             DMU_USERUSED_DNODE(os)->dn_type != 0) {
3746                 dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header,
3747                     NULL, 0);
3748                 dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header,
3749                     NULL, 0);
3750         }
3751
3752         if (DMU_PROJECTUSED_DNODE(os) != NULL &&
3753             DMU_PROJECTUSED_DNODE(os)->dn_type != 0)
3754                 dump_object(os, DMU_PROJECTUSED_OBJECT, verbosity,
3755                     &print_header, NULL, 0);
3756
3757         object = 0;
3758         while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
3759                 dump_object(os, object, verbosity, &print_header, &dnode_slots,
3760                     0);
3761                 object_count++;
3762                 total_slots_used += dnode_slots;
3763                 max_slot_used = object + dnode_slots - 1;
3764         }
3765
3766         (void) printf("\n");
3767
3768         (void) printf("    Dnode slots:\n");
3769         (void) printf("\tTotal used:    %10llu\n",
3770             (u_longlong_t)total_slots_used);
3771         (void) printf("\tMax used:      %10llu\n",
3772             (u_longlong_t)max_slot_used);
3773         (void) printf("\tPercent empty: %10lf\n",
3774             (double)(max_slot_used - total_slots_used)*100 /
3775             (double)max_slot_used);
3776         (void) printf("\n");
3777
3778         if (error != ESRCH) {
3779                 (void) fprintf(stderr, "dmu_object_next() = %d\n", error);
3780                 abort();
3781         }
3782
3783         ASSERT3U(object_count, ==, usedobjs);
3784
3785         if (leaked_objects != 0) {
3786                 (void) printf("%d potentially leaked objects detected\n",
3787                     leaked_objects);
3788                 leaked_objects = 0;
3789         }
3790 }
3791
3792 static void
3793 dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
3794 {
3795         time_t timestamp = ub->ub_timestamp;
3796
3797         (void) printf("%s", header ? header : "");
3798         (void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
3799         (void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
3800         (void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
3801         (void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
3802         (void) printf("\ttimestamp = %llu UTC = %s",
3803             (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
3804
3805         (void) printf("\tmmp_magic = %016llx\n",
3806             (u_longlong_t)ub->ub_mmp_magic);
3807         if (MMP_VALID(ub)) {
3808                 (void) printf("\tmmp_delay = %0llu\n",
3809                     (u_longlong_t)ub->ub_mmp_delay);
3810                 if (MMP_SEQ_VALID(ub))
3811                         (void) printf("\tmmp_seq = %u\n",
3812                             (unsigned int) MMP_SEQ(ub));
3813                 if (MMP_FAIL_INT_VALID(ub))
3814                         (void) printf("\tmmp_fail = %u\n",
3815                             (unsigned int) MMP_FAIL_INT(ub));
3816                 if (MMP_INTERVAL_VALID(ub))
3817                         (void) printf("\tmmp_write = %u\n",
3818                             (unsigned int) MMP_INTERVAL(ub));
3819                 /* After MMP_* to make summarize_uberblock_mmp cleaner */
3820                 (void) printf("\tmmp_valid = %x\n",
3821                     (unsigned int) ub->ub_mmp_config & 0xFF);
3822         }
3823
3824         if (dump_opt['u'] >= 4) {
3825                 char blkbuf[BP_SPRINTF_LEN];
3826                 snprintf_blkptr(blkbuf, sizeof (blkbuf), &ub->ub_rootbp);
3827                 (void) printf("\trootbp = %s\n", blkbuf);
3828         }
3829         (void) printf("\tcheckpoint_txg = %llu\n",
3830             (u_longlong_t)ub->ub_checkpoint_txg);
3831         (void) printf("%s", footer ? footer : "");
3832 }
3833
3834 static void
3835 dump_config(spa_t *spa)
3836 {
3837         dmu_buf_t *db;
3838         size_t nvsize = 0;
3839         int error = 0;
3840
3841
3842         error = dmu_bonus_hold(spa->spa_meta_objset,
3843             spa->spa_config_object, FTAG, &db);
3844
3845         if (error == 0) {
3846                 nvsize = *(uint64_t *)db->db_data;
3847                 dmu_buf_rele(db, FTAG);
3848
3849                 (void) printf("\nMOS Configuration:\n");
3850                 dump_packed_nvlist(spa->spa_meta_objset,
3851                     spa->spa_config_object, (void *)&nvsize, 1);
3852         } else {
3853                 (void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
3854                     (u_longlong_t)spa->spa_config_object, error);
3855         }
3856 }
3857
3858 static void
3859 dump_cachefile(const char *cachefile)
3860 {
3861         int fd;
3862         struct stat64 statbuf;
3863         char *buf;
3864         nvlist_t *config;
3865
3866         if ((fd = open64(cachefile, O_RDONLY)) < 0) {
3867                 (void) printf("cannot open '%s': %s\n", cachefile,
3868                     strerror(errno));
3869                 exit(1);
3870         }
3871
3872         if (fstat64(fd, &statbuf) != 0) {
3873                 (void) printf("failed to stat '%s': %s\n", cachefile,
3874                     strerror(errno));
3875                 exit(1);
3876         }
3877
3878         if ((buf = malloc(statbuf.st_size)) == NULL) {
3879                 (void) fprintf(stderr, "failed to allocate %llu bytes\n",
3880                     (u_longlong_t)statbuf.st_size);
3881                 exit(1);
3882         }
3883
3884         if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
3885                 (void) fprintf(stderr, "failed to read %llu bytes\n",
3886                     (u_longlong_t)statbuf.st_size);
3887                 exit(1);
3888         }
3889
3890         (void) close(fd);
3891
3892         if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
3893                 (void) fprintf(stderr, "failed to unpack nvlist\n");
3894                 exit(1);
3895         }
3896
3897         free(buf);
3898
3899         dump_nvlist(config, 0);
3900
3901         nvlist_free(config);
3902 }
3903
3904 /*
3905  * ZFS label nvlist stats
3906  */
3907 typedef struct zdb_nvl_stats {
3908         int             zns_list_count;
3909         int             zns_leaf_count;
3910         size_t          zns_leaf_largest;
3911         size_t          zns_leaf_total;
3912         nvlist_t        *zns_string;
3913         nvlist_t        *zns_uint64;
3914         nvlist_t        *zns_boolean;
3915 } zdb_nvl_stats_t;
3916
3917 static void
3918 collect_nvlist_stats(nvlist_t *nvl, zdb_nvl_stats_t *stats)
3919 {
3920         nvlist_t *list, **array;
3921         nvpair_t *nvp = NULL;
3922         char *name;
3923         uint_t i, items;
3924
3925         stats->zns_list_count++;
3926
3927         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
3928                 name = nvpair_name(nvp);
3929
3930                 switch (nvpair_type(nvp)) {
3931                 case DATA_TYPE_STRING:
3932                         fnvlist_add_string(stats->zns_string, name,
3933                             fnvpair_value_string(nvp));
3934                         break;
3935                 case DATA_TYPE_UINT64:
3936                         fnvlist_add_uint64(stats->zns_uint64, name,
3937                             fnvpair_value_uint64(nvp));
3938                         break;
3939                 case DATA_TYPE_BOOLEAN:
3940                         fnvlist_add_boolean(stats->zns_boolean, name);
3941                         break;
3942                 case DATA_TYPE_NVLIST:
3943                         if (nvpair_value_nvlist(nvp, &list) == 0)
3944                                 collect_nvlist_stats(list, stats);
3945                         break;
3946                 case DATA_TYPE_NVLIST_ARRAY:
3947                         if (nvpair_value_nvlist_array(nvp, &array, &items) != 0)
3948                                 break;
3949
3950                         for (i = 0; i < items; i++) {
3951                                 collect_nvlist_stats(array[i], stats);
3952
3953                                 /* collect stats on leaf vdev */
3954                                 if (strcmp(name, "children") == 0) {
3955                                         size_t size;
3956
3957                                         (void) nvlist_size(array[i], &size,
3958                                             NV_ENCODE_XDR);
3959                                         stats->zns_leaf_total += size;
3960                                         if (size > stats->zns_leaf_largest)
3961                                                 stats->zns_leaf_largest = size;
3962                                         stats->zns_leaf_count++;
3963                                 }
3964                         }
3965                         break;
3966                 default:
3967                         (void) printf("skip type %d!\n", (int)nvpair_type(nvp));
3968                 }
3969         }
3970 }
3971
3972 static void
3973 dump_nvlist_stats(nvlist_t *nvl, size_t cap)
3974 {
3975         zdb_nvl_stats_t stats = { 0 };
3976         size_t size, sum = 0, total;
3977         size_t noise;
3978
3979         /* requires nvlist with non-unique names for stat collection */
3980         VERIFY0(nvlist_alloc(&stats.zns_string, 0, 0));
3981         VERIFY0(nvlist_alloc(&stats.zns_uint64, 0, 0));
3982         VERIFY0(nvlist_alloc(&stats.zns_boolean, 0, 0));
3983         VERIFY0(nvlist_size(stats.zns_boolean, &noise, NV_ENCODE_XDR));
3984
3985         (void) printf("\n\nZFS Label NVList Config Stats:\n");
3986
3987         VERIFY0(nvlist_size(nvl, &total, NV_ENCODE_XDR));
3988         (void) printf("  %d bytes used, %d bytes free (using %4.1f%%)\n\n",
3989             (int)total, (int)(cap - total), 100.0 * total / cap);
3990
3991         collect_nvlist_stats(nvl, &stats);
3992
3993         VERIFY0(nvlist_size(stats.zns_uint64, &size, NV_ENCODE_XDR));
3994         size -= noise;
3995         sum += size;
3996         (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "integers:",
3997             (int)fnvlist_num_pairs(stats.zns_uint64),
3998             (int)size, 100.0 * size / total);
3999
4000         VERIFY0(nvlist_size(stats.zns_string, &size, NV_ENCODE_XDR));
4001         size -= noise;
4002         sum += size;
4003         (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "strings:",
4004             (int)fnvlist_num_pairs(stats.zns_string),
4005             (int)size, 100.0 * size / total);
4006
4007         VERIFY0(nvlist_size(stats.zns_boolean, &size, NV_ENCODE_XDR));
4008         size -= noise;
4009         sum += size;
4010         (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "booleans:",
4011             (int)fnvlist_num_pairs(stats.zns_boolean),
4012             (int)size, 100.0 * size / total);
4013
4014         size = total - sum;     /* treat remainder as nvlist overhead */
4015         (void) printf("%12s %4d %6d bytes (%5.2f%%)\n\n", "nvlists:",
4016             stats.zns_list_count, (int)size, 100.0 * size / total);
4017
4018         if (stats.zns_leaf_count > 0) {
4019                 size_t average = stats.zns_leaf_total / stats.zns_leaf_count;
4020
4021                 (void) printf("%12s %4d %6d bytes average\n", "leaf vdevs:",
4022                     stats.zns_leaf_count, (int)average);
4023                 (void) printf("%24d bytes largest\n",
4024                     (int)stats.zns_leaf_largest);
4025
4026                 if (dump_opt['l'] >= 3 && average > 0)
4027                         (void) printf("  space for %d additional leaf vdevs\n",
4028                             (int)((cap - total) / average));
4029         }
4030         (void) printf("\n");
4031
4032         nvlist_free(stats.zns_string);
4033         nvlist_free(stats.zns_uint64);
4034         nvlist_free(stats.zns_boolean);
4035 }
4036
4037 typedef struct cksum_record {
4038         zio_cksum_t cksum;
4039         boolean_t labels[VDEV_LABELS];
4040         avl_node_t link;
4041 } cksum_record_t;
4042
4043 static int
4044 cksum_record_compare(const void *x1, const void *x2)
4045 {
4046         const cksum_record_t *l = (cksum_record_t *)x1;
4047         const cksum_record_t *r = (cksum_record_t *)x2;
4048         int arraysize = ARRAY_SIZE(l->cksum.zc_word);
4049         int difference;
4050
4051         for (int i = 0; i < arraysize; i++) {
4052                 difference = TREE_CMP(l->cksum.zc_word[i], r->cksum.zc_word[i]);
4053                 if (difference)
4054                         break;
4055         }
4056
4057         return (difference);
4058 }
4059
4060 static cksum_record_t *
4061 cksum_record_alloc(zio_cksum_t *cksum, int l)
4062 {
4063         cksum_record_t *rec;
4064
4065         rec = umem_zalloc(sizeof (*rec), UMEM_NOFAIL);
4066         rec->cksum = *cksum;
4067         rec->labels[l] = B_TRUE;
4068
4069         return (rec);
4070 }
4071
4072 static cksum_record_t *
4073 cksum_record_lookup(avl_tree_t *tree, zio_cksum_t *cksum)
4074 {
4075         cksum_record_t lookup = { .cksum = *cksum };
4076         avl_index_t where;
4077
4078         return (avl_find(tree, &lookup, &where));
4079 }
4080
4081 static cksum_record_t *
4082 cksum_record_insert(avl_tree_t *tree, zio_cksum_t *cksum, int l)
4083 {
4084         cksum_record_t *rec;
4085
4086         rec = cksum_record_lookup(tree, cksum);
4087         if (rec) {
4088                 rec->labels[l] = B_TRUE;
4089         } else {
4090                 rec = cksum_record_alloc(cksum, l);
4091                 avl_add(tree, rec);
4092         }
4093
4094         return (rec);
4095 }
4096
4097 static int
4098 first_label(cksum_record_t *rec)
4099 {
4100         for (int i = 0; i < VDEV_LABELS; i++)
4101                 if (rec->labels[i])
4102                         return (i);
4103
4104         return (-1);
4105 }
4106
4107 static void
4108 print_label_numbers(char *prefix, cksum_record_t *rec)
4109 {
4110         printf("%s", prefix);
4111         for (int i = 0; i < VDEV_LABELS; i++)
4112                 if (rec->labels[i] == B_TRUE)
4113                         printf("%d ", i);
4114         printf("\n");
4115 }
4116
4117 #define MAX_UBERBLOCK_COUNT (VDEV_UBERBLOCK_RING >> UBERBLOCK_SHIFT)
4118
4119 typedef struct zdb_label {
4120         vdev_label_t label;
4121         nvlist_t *config_nv;
4122         cksum_record_t *config;
4123         cksum_record_t *uberblocks[MAX_UBERBLOCK_COUNT];
4124         boolean_t header_printed;
4125         boolean_t read_failed;
4126 } zdb_label_t;
4127
4128 static void
4129 print_label_header(zdb_label_t *label, int l)
4130 {
4131
4132         if (dump_opt['q'])
4133                 return;
4134
4135         if (label->header_printed == B_TRUE)
4136                 return;
4137
4138         (void) printf("------------------------------------\n");
4139         (void) printf("LABEL %d\n", l);
4140         (void) printf("------------------------------------\n");
4141
4142         label->header_printed = B_TRUE;
4143 }
4144
4145 static void
4146 print_l2arc_header(void)
4147 {
4148         (void) printf("------------------------------------\n");
4149         (void) printf("L2ARC device header\n");
4150         (void) printf("------------------------------------\n");
4151 }
4152
4153 static void
4154 print_l2arc_log_blocks(void)
4155 {
4156         (void) printf("------------------------------------\n");
4157         (void) printf("L2ARC device log blocks\n");
4158         (void) printf("------------------------------------\n");
4159 }
4160
4161 static void
4162 dump_l2arc_log_entries(uint64_t log_entries,
4163     l2arc_log_ent_phys_t *le, uint64_t i)
4164 {
4165         for (int j = 0; j < log_entries; j++) {
4166                 dva_t dva = le[j].le_dva;
4167                 (void) printf("lb[%4llu]\tle[%4d]\tDVA asize: %llu, "
4168                     "vdev: %llu, offset: %llu\n",
4169                     (u_longlong_t)i, j + 1,
4170                     (u_longlong_t)DVA_GET_ASIZE(&dva),
4171                     (u_longlong_t)DVA_GET_VDEV(&dva),
4172                     (u_longlong_t)DVA_GET_OFFSET(&dva));
4173                 (void) printf("|\t\t\t\tbirth: %llu\n",
4174                     (u_longlong_t)le[j].le_birth);
4175                 (void) printf("|\t\t\t\tlsize: %llu\n",
4176                     (u_longlong_t)L2BLK_GET_LSIZE((&le[j])->le_prop));
4177                 (void) printf("|\t\t\t\tpsize: %llu\n",
4178                     (u_longlong_t)L2BLK_GET_PSIZE((&le[j])->le_prop));
4179                 (void) printf("|\t\t\t\tcompr: %llu\n",
4180                     (u_longlong_t)L2BLK_GET_COMPRESS((&le[j])->le_prop));
4181                 (void) printf("|\t\t\t\tcomplevel: %llu\n",
4182                     (u_longlong_t)(&le[j])->le_complevel);
4183                 (void) printf("|\t\t\t\ttype: %llu\n",
4184                     (u_longlong_t)L2BLK_GET_TYPE((&le[j])->le_prop));
4185                 (void) printf("|\t\t\t\tprotected: %llu\n",
4186                     (u_longlong_t)L2BLK_GET_PROTECTED((&le[j])->le_prop));
4187                 (void) printf("|\t\t\t\tprefetch: %llu\n",
4188                     (u_longlong_t)L2BLK_GET_PREFETCH((&le[j])->le_prop));
4189                 (void) printf("|\t\t\t\taddress: %llu\n",
4190                     (u_longlong_t)le[j].le_daddr);
4191                 (void) printf("|\n");
4192         }
4193         (void) printf("\n");
4194 }
4195
4196 static void
4197 dump_l2arc_log_blkptr(l2arc_log_blkptr_t lbps)
4198 {
4199         (void) printf("|\t\tdaddr: %llu\n", (u_longlong_t)lbps.lbp_daddr);
4200         (void) printf("|\t\tpayload_asize: %llu\n",
4201             (u_longlong_t)lbps.lbp_payload_asize);
4202         (void) printf("|\t\tpayload_start: %llu\n",
4203             (u_longlong_t)lbps.lbp_payload_start);
4204         (void) printf("|\t\tlsize: %llu\n",
4205             (u_longlong_t)L2BLK_GET_LSIZE((&lbps)->lbp_prop));
4206         (void) printf("|\t\tasize: %llu\n",
4207             (u_longlong_t)L2BLK_GET_PSIZE((&lbps)->lbp_prop));
4208         (void) printf("|\t\tcompralgo: %llu\n",
4209             (u_longlong_t)L2BLK_GET_COMPRESS((&lbps)->lbp_prop));
4210         (void) printf("|\t\tcksumalgo: %llu\n",
4211             (u_longlong_t)L2BLK_GET_CHECKSUM((&lbps)->lbp_prop));
4212         (void) printf("|\n\n");
4213 }
4214
4215 static void
4216 dump_l2arc_log_blocks(int fd, l2arc_dev_hdr_phys_t l2dhdr,
4217     l2arc_dev_hdr_phys_t *rebuild)
4218 {
4219         l2arc_log_blk_phys_t this_lb;
4220         uint64_t asize;
4221         l2arc_log_blkptr_t lbps[2];
4222         abd_t *abd;
4223         zio_cksum_t cksum;
4224         int failed = 0;
4225         l2arc_dev_t dev;
4226
4227         if (!dump_opt['q'])
4228                 print_l2arc_log_blocks();
4229         bcopy((&l2dhdr)->dh_start_lbps, lbps, sizeof (lbps));
4230
4231         dev.l2ad_evict = l2dhdr.dh_evict;
4232         dev.l2ad_start = l2dhdr.dh_start;
4233         dev.l2ad_end = l2dhdr.dh_end;
4234
4235         if (l2dhdr.dh_start_lbps[0].lbp_daddr == 0) {
4236                 /* no log blocks to read */
4237                 if (!dump_opt['q']) {
4238                         (void) printf("No log blocks to read\n");
4239                         (void) printf("\n");
4240                 }
4241                 return;
4242         } else {
4243                 dev.l2ad_hand = lbps[0].lbp_daddr +
4244                     L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
4245         }
4246
4247         dev.l2ad_first = !!(l2dhdr.dh_flags & L2ARC_DEV_HDR_EVICT_FIRST);
4248
4249         for (;;) {
4250                 if (!l2arc_log_blkptr_valid(&dev, &lbps[0]))
4251                         break;
4252
4253                 /* L2BLK_GET_PSIZE returns aligned size for log blocks */
4254                 asize = L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
4255                 if (pread64(fd, &this_lb, asize, lbps[0].lbp_daddr) != asize) {
4256                         if (!dump_opt['q']) {
4257                                 (void) printf("Error while reading next log "
4258                                     "block\n\n");
4259                         }
4260                         break;
4261                 }
4262
4263                 fletcher_4_native_varsize(&this_lb, asize, &cksum);
4264                 if (!ZIO_CHECKSUM_EQUAL(cksum, lbps[0].lbp_cksum)) {
4265                         failed++;
4266                         if (!dump_opt['q']) {
4267                                 (void) printf("Invalid cksum\n");
4268                                 dump_l2arc_log_blkptr(lbps[0]);
4269                         }
4270                         break;
4271                 }
4272
4273                 switch (L2BLK_GET_COMPRESS((&lbps[0])->lbp_prop)) {
4274                 case ZIO_COMPRESS_OFF:
4275                         break;
4276                 default:
4277                         abd = abd_alloc_for_io(asize, B_TRUE);
4278                         abd_copy_from_buf_off(abd, &this_lb, 0, asize);
4279                         zio_decompress_data(L2BLK_GET_COMPRESS(
4280                             (&lbps[0])->lbp_prop), abd, &this_lb,
4281                             asize, sizeof (this_lb), NULL);
4282                         abd_free(abd);
4283                         break;
4284                 }
4285
4286                 if (this_lb.lb_magic == BSWAP_64(L2ARC_LOG_BLK_MAGIC))
4287                         byteswap_uint64_array(&this_lb, sizeof (this_lb));
4288                 if (this_lb.lb_magic != L2ARC_LOG_BLK_MAGIC) {
4289                         if (!dump_opt['q'])
4290                                 (void) printf("Invalid log block magic\n\n");
4291                         break;
4292                 }
4293
4294                 rebuild->dh_lb_count++;
4295                 rebuild->dh_lb_asize += asize;
4296                 if (dump_opt['l'] > 1 && !dump_opt['q']) {
4297                         (void) printf("lb[%4llu]\tmagic: %llu\n",
4298                             (u_longlong_t)rebuild->dh_lb_count,
4299                             (u_longlong_t)this_lb.lb_magic);
4300                         dump_l2arc_log_blkptr(lbps[0]);
4301                 }
4302
4303                 if (dump_opt['l'] > 2 && !dump_opt['q'])
4304                         dump_l2arc_log_entries(l2dhdr.dh_log_entries,
4305                             this_lb.lb_entries,
4306                             rebuild->dh_lb_count);
4307
4308                 if (l2arc_range_check_overlap(lbps[1].lbp_payload_start,
4309                     lbps[0].lbp_payload_start, dev.l2ad_evict) &&
4310                     !dev.l2ad_first)
4311                         break;
4312
4313                 lbps[0] = lbps[1];
4314                 lbps[1] = this_lb.lb_prev_lbp;
4315         }
4316
4317         if (!dump_opt['q']) {
4318                 (void) printf("log_blk_count:\t %llu with valid cksum\n",
4319                     (u_longlong_t)rebuild->dh_lb_count);
4320                 (void) printf("\t\t %d with invalid cksum\n", failed);
4321                 (void) printf("log_blk_asize:\t %llu\n\n",
4322                     (u_longlong_t)rebuild->dh_lb_asize);
4323         }
4324 }
4325
4326 static int
4327 dump_l2arc_header(int fd)
4328 {
4329         l2arc_dev_hdr_phys_t l2dhdr, rebuild;
4330         int error = B_FALSE;
4331
4332         bzero(&l2dhdr, sizeof (l2dhdr));
4333         bzero(&rebuild, sizeof (rebuild));
4334
4335         if (pread64(fd, &l2dhdr, sizeof (l2dhdr),
4336             VDEV_LABEL_START_SIZE) != sizeof (l2dhdr)) {
4337                 error = B_TRUE;
4338         } else {
4339                 if (l2dhdr.dh_magic == BSWAP_64(L2ARC_DEV_HDR_MAGIC))
4340                         byteswap_uint64_array(&l2dhdr, sizeof (l2dhdr));
4341
4342                 if (l2dhdr.dh_magic != L2ARC_DEV_HDR_MAGIC)
4343                         error = B_TRUE;
4344         }
4345
4346         if (error) {
4347                 (void) printf("L2ARC device header not found\n\n");
4348                 /* Do not return an error here for backward compatibility */
4349                 return (0);
4350         } else if (!dump_opt['q']) {
4351                 print_l2arc_header();
4352
4353                 (void) printf("    magic: %llu\n",
4354                     (u_longlong_t)l2dhdr.dh_magic);
4355                 (void) printf("    version: %llu\n",
4356                     (u_longlong_t)l2dhdr.dh_version);
4357                 (void) printf("    pool_guid: %llu\n",
4358                     (u_longlong_t)l2dhdr.dh_spa_guid);
4359                 (void) printf("    flags: %llu\n",
4360                     (u_longlong_t)l2dhdr.dh_flags);
4361                 (void) printf("    start_lbps[0]: %llu\n",
4362                     (u_longlong_t)
4363                     l2dhdr.dh_start_lbps[0].lbp_daddr);
4364                 (void) printf("    start_lbps[1]: %llu\n",
4365                     (u_longlong_t)
4366                     l2dhdr.dh_start_lbps[1].lbp_daddr);
4367                 (void) printf("    log_blk_ent: %llu\n",
4368                     (u_longlong_t)l2dhdr.dh_log_entries);
4369                 (void) printf("    start: %llu\n",
4370                     (u_longlong_t)l2dhdr.dh_start);
4371                 (void) printf("    end: %llu\n",
4372                     (u_longlong_t)l2dhdr.dh_end);
4373                 (void) printf("    evict: %llu\n",
4374                     (u_longlong_t)l2dhdr.dh_evict);
4375                 (void) printf("    lb_asize_refcount: %llu\n",
4376                     (u_longlong_t)l2dhdr.dh_lb_asize);
4377                 (void) printf("    lb_count_refcount: %llu\n",
4378                     (u_longlong_t)l2dhdr.dh_lb_count);
4379                 (void) printf("    trim_action_time: %llu\n",
4380                     (u_longlong_t)l2dhdr.dh_trim_action_time);
4381                 (void) printf("    trim_state: %llu\n\n",
4382                     (u_longlong_t)l2dhdr.dh_trim_state);
4383         }
4384
4385         dump_l2arc_log_blocks(fd, l2dhdr, &rebuild);
4386         /*
4387          * The total aligned size of log blocks and the number of log blocks
4388          * reported in the header of the device may be less than what zdb
4389          * reports by dump_l2arc_log_blocks() which emulates l2arc_rebuild().
4390          * This happens because dump_l2arc_log_blocks() lacks the memory
4391          * pressure valve that l2arc_rebuild() has. Thus, if we are on a system
4392          * with low memory, l2arc_rebuild will exit prematurely and dh_lb_asize
4393          * and dh_lb_count will be lower to begin with than what exists on the
4394          * device. This is normal and zdb should not exit with an error. The
4395          * opposite case should never happen though, the values reported in the
4396          * header should never be higher than what dump_l2arc_log_blocks() and
4397          * l2arc_rebuild() report. If this happens there is a leak in the
4398          * accounting of log blocks.
4399          */
4400         if (l2dhdr.dh_lb_asize > rebuild.dh_lb_asize ||
4401             l2dhdr.dh_lb_count > rebuild.dh_lb_count)
4402                 return (1);
4403
4404         return (0);
4405 }
4406
4407 static void
4408 dump_config_from_label(zdb_label_t *label, size_t buflen, int l)
4409 {
4410         if (dump_opt['q'])
4411                 return;
4412
4413         if ((dump_opt['l'] < 3) && (first_label(label->config) != l))
4414                 return;
4415
4416         print_label_header(label, l);
4417         dump_nvlist(label->config_nv, 4);
4418         print_label_numbers("    labels = ", label->config);
4419
4420         if (dump_opt['l'] >= 2)
4421                 dump_nvlist_stats(label->config_nv, buflen);
4422 }
4423
4424 #define ZDB_MAX_UB_HEADER_SIZE 32
4425
4426 static void
4427 dump_label_uberblocks(zdb_label_t *label, uint64_t ashift, int label_num)
4428 {
4429
4430         vdev_t vd;
4431         char header[ZDB_MAX_UB_HEADER_SIZE];
4432
4433         vd.vdev_ashift = ashift;
4434         vd.vdev_top = &vd;
4435
4436         for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
4437                 uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
4438                 uberblock_t *ub = (void *)((char *)&label->label + uoff);
4439                 cksum_record_t *rec = label->uberblocks[i];
4440
4441                 if (rec == NULL) {
4442                         if (dump_opt['u'] >= 2) {
4443                                 print_label_header(label, label_num);
4444                                 (void) printf("    Uberblock[%d] invalid\n", i);
4445                         }
4446                         continue;
4447                 }
4448
4449                 if ((dump_opt['u'] < 3) && (first_label(rec) != label_num))
4450                         continue;
4451
4452                 if ((dump_opt['u'] < 4) &&
4453                     (ub->ub_mmp_magic == MMP_MAGIC) && ub->ub_mmp_delay &&
4454                     (i >= VDEV_UBERBLOCK_COUNT(&vd) - MMP_BLOCKS_PER_LABEL))
4455                         continue;
4456
4457                 print_label_header(label, label_num);
4458                 (void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
4459                     "    Uberblock[%d]\n", i);
4460                 dump_uberblock(ub, header, "");
4461                 print_label_numbers("        labels = ", rec);
4462         }
4463 }
4464
4465 static char curpath[PATH_MAX];
4466
4467 /*
4468  * Iterate through the path components, recursively passing
4469  * current one's obj and remaining path until we find the obj
4470  * for the last one.
4471  */
4472 static int
4473 dump_path_impl(objset_t *os, uint64_t obj, char *name)
4474 {
4475         int err;
4476         boolean_t header = B_TRUE;
4477         uint64_t child_obj;
4478         char *s;
4479         dmu_buf_t *db;
4480         dmu_object_info_t doi;
4481
4482         if ((s = strchr(name, '/')) != NULL)
4483                 *s = '\0';
4484         err = zap_lookup(os, obj, name, 8, 1, &child_obj);
4485
4486         (void) strlcat(curpath, name, sizeof (curpath));
4487
4488         if (err != 0) {
4489                 (void) fprintf(stderr, "failed to lookup %s: %s\n",
4490                     curpath, strerror(err));
4491                 return (err);
4492         }
4493
4494         child_obj = ZFS_DIRENT_OBJ(child_obj);
4495         err = sa_buf_hold(os, child_obj, FTAG, &db);
4496         if (err != 0) {
4497                 (void) fprintf(stderr,
4498                     "failed to get SA dbuf for obj %llu: %s\n",
4499                     (u_longlong_t)child_obj, strerror(err));
4500                 return (EINVAL);
4501         }
4502         dmu_object_info_from_db(db, &doi);
4503         sa_buf_rele(db, FTAG);
4504
4505         if (doi.doi_bonus_type != DMU_OT_SA &&
4506             doi.doi_bonus_type != DMU_OT_ZNODE) {
4507                 (void) fprintf(stderr, "invalid bonus type %d for obj %llu\n",
4508                     doi.doi_bonus_type, (u_longlong_t)child_obj);
4509                 return (EINVAL);
4510         }
4511
4512         if (dump_opt['v'] > 6) {
4513                 (void) printf("obj=%llu %s type=%d bonustype=%d\n",
4514                     (u_longlong_t)child_obj, curpath, doi.doi_type,
4515                     doi.doi_bonus_type);
4516         }
4517
4518         (void) strlcat(curpath, "/", sizeof (curpath));
4519
4520         switch (doi.doi_type) {
4521         case DMU_OT_DIRECTORY_CONTENTS:
4522                 if (s != NULL && *(s + 1) != '\0')
4523                         return (dump_path_impl(os, child_obj, s + 1));
4524                 /*FALLTHROUGH*/
4525         case DMU_OT_PLAIN_FILE_CONTENTS:
4526                 dump_object(os, child_obj, dump_opt['v'], &header, NULL, 0);
4527                 return (0);
4528         default:
4529                 (void) fprintf(stderr, "object %llu has non-file/directory "
4530                     "type %d\n", (u_longlong_t)obj, doi.doi_type);
4531                 break;
4532         }
4533
4534         return (EINVAL);
4535 }
4536
4537 /*
4538  * Dump the blocks for the object specified by path inside the dataset.
4539  */
4540 static int
4541 dump_path(char *ds, char *path)
4542 {
4543         int err;
4544         objset_t *os;
4545         uint64_t root_obj;
4546
4547         err = open_objset(ds, FTAG, &os);
4548         if (err != 0)
4549                 return (err);
4550
4551         err = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1, &root_obj);
4552         if (err != 0) {
4553                 (void) fprintf(stderr, "can't lookup root znode: %s\n",
4554                     strerror(err));
4555                 close_objset(os, FTAG);
4556                 return (EINVAL);
4557         }
4558
4559         (void) snprintf(curpath, sizeof (curpath), "dataset=%s path=/", ds);
4560
4561         err = dump_path_impl(os, root_obj, path);
4562
4563         close_objset(os, FTAG);
4564         return (err);
4565 }
4566
4567 static int
4568 dump_label(const char *dev)
4569 {
4570         char path[MAXPATHLEN];
4571         zdb_label_t labels[VDEV_LABELS];
4572         uint64_t psize, ashift, l2cache;
4573         struct stat64 statbuf;
4574         boolean_t config_found = B_FALSE;
4575         boolean_t error = B_FALSE;
4576         boolean_t read_l2arc_header = B_FALSE;
4577         avl_tree_t config_tree;
4578         avl_tree_t uberblock_tree;
4579         void *node, *cookie;
4580         int fd;
4581
4582         bzero(labels, sizeof (labels));
4583
4584         /*
4585          * Check if we were given absolute path and use it as is.
4586          * Otherwise if the provided vdev name doesn't point to a file,
4587          * try prepending expected disk paths and partition numbers.
4588          */
4589         (void) strlcpy(path, dev, sizeof (path));
4590         if (dev[0] != '/' && stat64(path, &statbuf) != 0) {
4591                 int error;
4592
4593                 error = zfs_resolve_shortname(dev, path, MAXPATHLEN);
4594                 if (error == 0 && zfs_dev_is_whole_disk(path)) {
4595                         if (zfs_append_partition(path, MAXPATHLEN) == -1)
4596                                 error = ENOENT;
4597                 }
4598
4599                 if (error || (stat64(path, &statbuf) != 0)) {
4600                         (void) printf("failed to find device %s, try "
4601                             "specifying absolute path instead\n", dev);
4602                         return (1);
4603                 }
4604         }
4605
4606         if ((fd = open64(path, O_RDONLY)) < 0) {
4607                 (void) printf("cannot open '%s': %s\n", path, strerror(errno));
4608                 exit(1);
4609         }
4610
4611         if (fstat64_blk(fd, &statbuf) != 0) {
4612                 (void) printf("failed to stat '%s': %s\n", path,
4613                     strerror(errno));
4614                 (void) close(fd);
4615                 exit(1);
4616         }
4617
4618         if (S_ISBLK(statbuf.st_mode) && zfs_dev_flush(fd) != 0)
4619                 (void) printf("failed to invalidate cache '%s' : %s\n", path,
4620                     strerror(errno));
4621
4622         avl_create(&config_tree, cksum_record_compare,
4623             sizeof (cksum_record_t), offsetof(cksum_record_t, link));
4624         avl_create(&uberblock_tree, cksum_record_compare,
4625             sizeof (cksum_record_t), offsetof(cksum_record_t, link));
4626
4627         psize = statbuf.st_size;
4628         psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
4629         ashift = SPA_MINBLOCKSHIFT;
4630
4631         /*
4632          * 1. Read the label from disk
4633          * 2. Unpack the configuration and insert in config tree.
4634          * 3. Traverse all uberblocks and insert in uberblock tree.
4635          */
4636         for (int l = 0; l < VDEV_LABELS; l++) {
4637                 zdb_label_t *label = &labels[l];
4638                 char *buf = label->label.vl_vdev_phys.vp_nvlist;
4639                 size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
4640                 nvlist_t *config;
4641                 cksum_record_t *rec;
4642                 zio_cksum_t cksum;
4643                 vdev_t vd;
4644
4645                 if (pread64(fd, &label->label, sizeof (label->label),
4646                     vdev_label_offset(psize, l, 0)) != sizeof (label->label)) {
4647                         if (!dump_opt['q'])
4648                                 (void) printf("failed to read label %d\n", l);
4649                         label->read_failed = B_TRUE;
4650                         error = B_TRUE;
4651                         continue;
4652                 }
4653
4654                 label->read_failed = B_FALSE;
4655
4656                 if (nvlist_unpack(buf, buflen, &config, 0) == 0) {
4657                         nvlist_t *vdev_tree = NULL;
4658                         size_t size;
4659
4660                         if ((nvlist_lookup_nvlist(config,
4661                             ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
4662                             (nvlist_lookup_uint64(vdev_tree,
4663                             ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
4664                                 ashift = SPA_MINBLOCKSHIFT;
4665
4666                         if (nvlist_size(config, &size, NV_ENCODE_XDR) != 0)
4667                                 size = buflen;
4668
4669                         /* If the device is a cache device clear the header. */
4670                         if (!read_l2arc_header) {
4671                                 if (nvlist_lookup_uint64(config,
4672                                     ZPOOL_CONFIG_POOL_STATE, &l2cache) == 0 &&
4673                                     l2cache == POOL_STATE_L2CACHE) {
4674                                         read_l2arc_header = B_TRUE;
4675                                 }
4676                         }
4677
4678                         fletcher_4_native_varsize(buf, size, &cksum);
4679                         rec = cksum_record_insert(&config_tree, &cksum, l);
4680
4681                         label->config = rec;
4682                         label->config_nv = config;
4683                         config_found = B_TRUE;
4684                 } else {
4685                         error = B_TRUE;
4686                 }
4687
4688                 vd.vdev_ashift = ashift;
4689                 vd.vdev_top = &vd;
4690
4691                 for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
4692                         uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
4693                         uberblock_t *ub = (void *)((char *)label + uoff);
4694
4695                         if (uberblock_verify(ub))
4696                                 continue;
4697
4698                         fletcher_4_native_varsize(ub, sizeof (*ub), &cksum);
4699                         rec = cksum_record_insert(&uberblock_tree, &cksum, l);
4700
4701                         label->uberblocks[i] = rec;
4702                 }
4703         }
4704
4705         /*
4706          * Dump the label and uberblocks.
4707          */
4708         for (int l = 0; l < VDEV_LABELS; l++) {
4709                 zdb_label_t *label = &labels[l];
4710                 size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
4711
4712                 if (label->read_failed == B_TRUE)
4713                         continue;
4714
4715                 if (label->config_nv) {
4716                         dump_config_from_label(label, buflen, l);
4717                 } else {
4718                         if (!dump_opt['q'])
4719                                 (void) printf("failed to unpack label %d\n", l);
4720                 }
4721
4722                 if (dump_opt['u'])
4723                         dump_label_uberblocks(label, ashift, l);
4724
4725                 nvlist_free(label->config_nv);
4726         }
4727
4728         /*
4729          * Dump the L2ARC header, if existent.
4730          */
4731         if (read_l2arc_header)
4732                 error |= dump_l2arc_header(fd);
4733
4734         cookie = NULL;
4735         while ((node = avl_destroy_nodes(&config_tree, &cookie)) != NULL)
4736                 umem_free(node, sizeof (cksum_record_t));
4737
4738         cookie = NULL;
4739         while ((node = avl_destroy_nodes(&uberblock_tree, &cookie)) != NULL)
4740                 umem_free(node, sizeof (cksum_record_t));
4741
4742         avl_destroy(&config_tree);
4743         avl_destroy(&uberblock_tree);
4744
4745         (void) close(fd);
4746
4747         return (config_found == B_FALSE ? 2 :
4748             (error == B_TRUE ? 1 : 0));
4749 }
4750
4751 static uint64_t dataset_feature_count[SPA_FEATURES];
4752 static uint64_t global_feature_count[SPA_FEATURES];
4753 static uint64_t remap_deadlist_count = 0;
4754
4755 /*ARGSUSED*/
4756 static int
4757 dump_one_objset(const char *dsname, void *arg)
4758 {
4759         int error;
4760         objset_t *os;
4761         spa_feature_t f;
4762
4763         error = open_objset(dsname, FTAG, &os);
4764         if (error != 0)
4765                 return (0);
4766
4767         for (f = 0; f < SPA_FEATURES; f++) {
4768                 if (!dsl_dataset_feature_is_active(dmu_objset_ds(os), f))
4769                         continue;
4770                 ASSERT(spa_feature_table[f].fi_flags &
4771                     ZFEATURE_FLAG_PER_DATASET);
4772                 dataset_feature_count[f]++;
4773         }
4774
4775         if (dsl_dataset_remap_deadlist_exists(dmu_objset_ds(os))) {
4776                 remap_deadlist_count++;
4777         }
4778
4779         for (dsl_bookmark_node_t *dbn =
4780             avl_first(&dmu_objset_ds(os)->ds_bookmarks); dbn != NULL;
4781             dbn = AVL_NEXT(&dmu_objset_ds(os)->ds_bookmarks, dbn)) {
4782                 mos_obj_refd(dbn->dbn_phys.zbm_redaction_obj);
4783                 if (dbn->dbn_phys.zbm_redaction_obj != 0)
4784                         global_feature_count[SPA_FEATURE_REDACTION_BOOKMARKS]++;
4785                 if (dbn->dbn_phys.zbm_flags & ZBM_FLAG_HAS_FBN)
4786                         global_feature_count[SPA_FEATURE_BOOKMARK_WRITTEN]++;
4787         }
4788
4789         if (dsl_deadlist_is_open(&dmu_objset_ds(os)->ds_dir->dd_livelist) &&
4790             !dmu_objset_is_snapshot(os)) {
4791                 global_feature_count[SPA_FEATURE_LIVELIST]++;
4792         }
4793
4794         dump_objset(os);
4795         close_objset(os, FTAG);
4796         fuid_table_destroy();
4797         return (0);
4798 }
4799
4800 /*
4801  * Block statistics.
4802  */
4803 #define PSIZE_HISTO_SIZE (SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 2)
4804 typedef struct zdb_blkstats {
4805         uint64_t zb_asize;
4806         uint64_t zb_lsize;
4807         uint64_t zb_psize;
4808         uint64_t zb_count;
4809         uint64_t zb_gangs;
4810         uint64_t zb_ditto_samevdev;
4811         uint64_t zb_ditto_same_ms;
4812         uint64_t zb_psize_histogram[PSIZE_HISTO_SIZE];
4813 } zdb_blkstats_t;
4814
4815 /*
4816  * Extended object types to report deferred frees and dedup auto-ditto blocks.
4817  */
4818 #define ZDB_OT_DEFERRED (DMU_OT_NUMTYPES + 0)
4819 #define ZDB_OT_DITTO    (DMU_OT_NUMTYPES + 1)
4820 #define ZDB_OT_OTHER    (DMU_OT_NUMTYPES + 2)
4821 #define ZDB_OT_TOTAL    (DMU_OT_NUMTYPES + 3)
4822
4823 static const char *zdb_ot_extname[] = {
4824         "deferred free",
4825         "dedup ditto",
4826         "other",
4827         "Total",
4828 };
4829
4830 #define ZB_TOTAL        DN_MAX_LEVELS
4831 #define SPA_MAX_FOR_16M (SPA_MAXBLOCKSHIFT+1)
4832
4833 typedef struct zdb_cb {
4834         zdb_blkstats_t  zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
4835         uint64_t        zcb_removing_size;
4836         uint64_t        zcb_checkpoint_size;
4837         uint64_t        zcb_dedup_asize;
4838         uint64_t        zcb_dedup_blocks;
4839         uint64_t        zcb_psize_count[SPA_MAX_FOR_16M];
4840         uint64_t        zcb_lsize_count[SPA_MAX_FOR_16M];
4841         uint64_t        zcb_asize_count[SPA_MAX_FOR_16M];
4842         uint64_t        zcb_psize_len[SPA_MAX_FOR_16M];
4843         uint64_t        zcb_lsize_len[SPA_MAX_FOR_16M];
4844         uint64_t        zcb_asize_len[SPA_MAX_FOR_16M];
4845         uint64_t        zcb_psize_total;
4846         uint64_t        zcb_lsize_total;
4847         uint64_t        zcb_asize_total;
4848         uint64_t        zcb_embedded_blocks[NUM_BP_EMBEDDED_TYPES];
4849         uint64_t        zcb_embedded_histogram[NUM_BP_EMBEDDED_TYPES]
4850             [BPE_PAYLOAD_SIZE + 1];
4851         uint64_t        zcb_start;
4852         hrtime_t        zcb_lastprint;
4853         uint64_t        zcb_totalasize;
4854         uint64_t        zcb_errors[256];
4855         int             zcb_readfails;
4856         int             zcb_haderrors;
4857         spa_t           *zcb_spa;
4858         uint32_t        **zcb_vd_obsolete_counts;
4859 } zdb_cb_t;
4860
4861 /* test if two DVA offsets from same vdev are within the same metaslab */
4862 static boolean_t
4863 same_metaslab(spa_t *spa, uint64_t vdev, uint64_t off1, uint64_t off2)
4864 {
4865         vdev_t *vd = vdev_lookup_top(spa, vdev);
4866         uint64_t ms_shift = vd->vdev_ms_shift;
4867
4868         return ((off1 >> ms_shift) == (off2 >> ms_shift));
4869 }
4870
4871 /*
4872  * Used to simplify reporting of the histogram data.
4873  */
4874 typedef struct one_histo {
4875         char *name;
4876         uint64_t *count;
4877         uint64_t *len;
4878         uint64_t cumulative;
4879 } one_histo_t;
4880
4881 /*
4882  * The number of separate histograms processed for psize, lsize and asize.
4883  */
4884 #define NUM_HISTO 3
4885
4886 /*
4887  * This routine will create a fixed column size output of three different
4888  * histograms showing by blocksize of 512 - 2^ SPA_MAX_FOR_16M
4889  * the count, length and cumulative length of the psize, lsize and
4890  * asize blocks.
4891  *
4892  * All three types of blocks are listed on a single line
4893  *
4894  * By default the table is printed in nicenumber format (e.g. 123K) but
4895  * if the '-P' parameter is specified then the full raw number (parseable)
4896  * is printed out.
4897  */
4898 static void
4899 dump_size_histograms(zdb_cb_t *zcb)
4900 {
4901         /*
4902          * A temporary buffer that allows us to convert a number into
4903          * a string using zdb_nicenumber to allow either raw or human
4904          * readable numbers to be output.
4905          */
4906         char numbuf[32];
4907
4908         /*
4909          * Define titles which are used in the headers of the tables
4910          * printed by this routine.
4911          */
4912         const char blocksize_title1[] = "block";
4913         const char blocksize_title2[] = "size";
4914         const char count_title[] = "Count";
4915         const char length_title[] = "Size";
4916         const char cumulative_title[] = "Cum.";
4917
4918         /*
4919          * Setup the histogram arrays (psize, lsize, and asize).
4920          */
4921         one_histo_t parm_histo[NUM_HISTO];
4922
4923         parm_histo[0].name = "psize";
4924         parm_histo[0].count = zcb->zcb_psize_count;
4925         parm_histo[0].len = zcb->zcb_psize_len;
4926         parm_histo[0].cumulative = 0;
4927
4928         parm_histo[1].name = "lsize";
4929         parm_histo[1].count = zcb->zcb_lsize_count;
4930         parm_histo[1].len = zcb->zcb_lsize_len;
4931         parm_histo[1].cumulative = 0;
4932
4933         parm_histo[2].name = "asize";
4934         parm_histo[2].count = zcb->zcb_asize_count;
4935         parm_histo[2].len = zcb->zcb_asize_len;
4936         parm_histo[2].cumulative = 0;
4937
4938
4939         (void) printf("\nBlock Size Histogram\n");
4940         /*
4941          * Print the first line titles
4942          */
4943         if (dump_opt['P'])
4944                 (void) printf("\n%s\t", blocksize_title1);
4945         else
4946                 (void) printf("\n%7s   ", blocksize_title1);
4947
4948         for (int j = 0; j < NUM_HISTO; j++) {
4949                 if (dump_opt['P']) {
4950                         if (j < NUM_HISTO - 1) {
4951                                 (void) printf("%s\t\t\t", parm_histo[j].name);
4952                         } else {
4953                                 /* Don't print trailing spaces */
4954                                 (void) printf("  %s", parm_histo[j].name);
4955                         }
4956                 } else {
4957                         if (j < NUM_HISTO - 1) {
4958                                 /* Left aligned strings in the output */
4959                                 (void) printf("%-7s              ",
4960                                     parm_histo[j].name);
4961                         } else {
4962                                 /* Don't print trailing spaces */
4963                                 (void) printf("%s", parm_histo[j].name);
4964                         }
4965                 }
4966         }
4967         (void) printf("\n");
4968
4969         /*
4970          * Print the second line titles
4971          */
4972         if (dump_opt['P']) {
4973                 (void) printf("%s\t", blocksize_title2);
4974         } else {
4975                 (void) printf("%7s ", blocksize_title2);
4976         }
4977
4978         for (int i = 0; i < NUM_HISTO; i++) {
4979                 if (dump_opt['P']) {
4980                         (void) printf("%s\t%s\t%s\t",
4981                             count_title, length_title, cumulative_title);
4982                 } else {
4983                         (void) printf("%7s%7s%7s",
4984                             count_title, length_title, cumulative_title);
4985                 }
4986         }
4987         (void) printf("\n");
4988
4989         /*
4990          * Print the rows
4991          */
4992         for (int i = SPA_MINBLOCKSHIFT; i < SPA_MAX_FOR_16M; i++) {
4993
4994                 /*
4995                  * Print the first column showing the blocksize
4996                  */
4997                 zdb_nicenum((1ULL << i), numbuf, sizeof (numbuf));
4998
4999                 if (dump_opt['P']) {
5000                         printf("%s", numbuf);
5001                 } else {
5002                         printf("%7s:", numbuf);
5003                 }
5004
5005                 /*
5006                  * Print the remaining set of 3 columns per size:
5007                  * for psize, lsize and asize
5008                  */
5009                 for (int j = 0; j < NUM_HISTO; j++) {
5010                         parm_histo[j].cumulative += parm_histo[j].len[i];
5011
5012                         zdb_nicenum(parm_histo[j].count[i],
5013                             numbuf, sizeof (numbuf));
5014                         if (dump_opt['P'])
5015                                 (void) printf("\t%s", numbuf);
5016                         else
5017                                 (void) printf("%7s", numbuf);
5018
5019                         zdb_nicenum(parm_histo[j].len[i],
5020                             numbuf, sizeof (numbuf));
5021                         if (dump_opt['P'])
5022                                 (void) printf("\t%s", numbuf);
5023                         else
5024                                 (void) printf("%7s", numbuf);
5025
5026                         zdb_nicenum(parm_histo[j].cumulative,
5027                             numbuf, sizeof (numbuf));
5028                         if (dump_opt['P'])
5029                                 (void) printf("\t%s", numbuf);
5030                         else
5031                                 (void) printf("%7s", numbuf);
5032                 }
5033                 (void) printf("\n");
5034         }
5035 }
5036
5037 static void
5038 zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
5039     dmu_object_type_t type)
5040 {
5041         uint64_t refcnt = 0;
5042         int i;
5043
5044         ASSERT(type < ZDB_OT_TOTAL);
5045
5046         if (zilog && zil_bp_tree_add(zilog, bp) != 0)
5047                 return;
5048
5049         spa_config_enter(zcb->zcb_spa, SCL_CONFIG, FTAG, RW_READER);
5050
5051         for (i = 0; i < 4; i++) {
5052                 int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
5053                 int t = (i & 1) ? type : ZDB_OT_TOTAL;
5054                 int equal;
5055                 zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
5056
5057                 zb->zb_asize += BP_GET_ASIZE(bp);
5058                 zb->zb_lsize += BP_GET_LSIZE(bp);
5059                 zb->zb_psize += BP_GET_PSIZE(bp);
5060                 zb->zb_count++;
5061
5062                 /*
5063                  * The histogram is only big enough to record blocks up to
5064                  * SPA_OLD_MAXBLOCKSIZE; larger blocks go into the last,
5065                  * "other", bucket.
5066                  */
5067                 unsigned idx = BP_GET_PSIZE(bp) >> SPA_MINBLOCKSHIFT;
5068                 idx = MIN(idx, SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 1);
5069                 zb->zb_psize_histogram[idx]++;
5070
5071                 zb->zb_gangs += BP_COUNT_GANG(bp);
5072
5073                 switch (BP_GET_NDVAS(bp)) {
5074                 case 2:
5075                         if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5076                             DVA_GET_VDEV(&bp->blk_dva[1])) {
5077                                 zb->zb_ditto_samevdev++;
5078
5079                                 if (same_metaslab(zcb->zcb_spa,
5080                                     DVA_GET_VDEV(&bp->blk_dva[0]),
5081                                     DVA_GET_OFFSET(&bp->blk_dva[0]),
5082                                     DVA_GET_OFFSET(&bp->blk_dva[1])))
5083                                         zb->zb_ditto_same_ms++;
5084                         }
5085                         break;
5086                 case 3:
5087                         equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5088                             DVA_GET_VDEV(&bp->blk_dva[1])) +
5089                             (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5090                             DVA_GET_VDEV(&bp->blk_dva[2])) +
5091                             (DVA_GET_VDEV(&bp->blk_dva[1]) ==
5092                             DVA_GET_VDEV(&bp->blk_dva[2]));
5093                         if (equal != 0) {
5094                                 zb->zb_ditto_samevdev++;
5095
5096                                 if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5097                                     DVA_GET_VDEV(&bp->blk_dva[1]) &&
5098                                     same_metaslab(zcb->zcb_spa,
5099                                     DVA_GET_VDEV(&bp->blk_dva[0]),
5100                                     DVA_GET_OFFSET(&bp->blk_dva[0]),
5101                                     DVA_GET_OFFSET(&bp->blk_dva[1])))
5102                                         zb->zb_ditto_same_ms++;
5103                                 else if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5104                                     DVA_GET_VDEV(&bp->blk_dva[2]) &&
5105                                     same_metaslab(zcb->zcb_spa,
5106                                     DVA_GET_VDEV(&bp->blk_dva[0]),
5107                                     DVA_GET_OFFSET(&bp->blk_dva[0]),
5108                                     DVA_GET_OFFSET(&bp->blk_dva[2])))
5109                                         zb->zb_ditto_same_ms++;
5110                                 else if (DVA_GET_VDEV(&bp->blk_dva[1]) ==
5111                                     DVA_GET_VDEV(&bp->blk_dva[2]) &&
5112                                     same_metaslab(zcb->zcb_spa,
5113                                     DVA_GET_VDEV(&bp->blk_dva[1]),
5114                                     DVA_GET_OFFSET(&bp->blk_dva[1]),
5115                                     DVA_GET_OFFSET(&bp->blk_dva[2])))
5116                                         zb->zb_ditto_same_ms++;
5117                         }
5118                         break;
5119                 }
5120         }
5121
5122         spa_config_exit(zcb->zcb_spa, SCL_CONFIG, FTAG);
5123
5124         if (BP_IS_EMBEDDED(bp)) {
5125                 zcb->zcb_embedded_blocks[BPE_GET_ETYPE(bp)]++;
5126                 zcb->zcb_embedded_histogram[BPE_GET_ETYPE(bp)]
5127                     [BPE_GET_PSIZE(bp)]++;
5128                 return;
5129         }
5130         /*
5131          * The binning histogram bins by powers of two up to
5132          * SPA_MAXBLOCKSIZE rather than creating bins for
5133          * every possible blocksize found in the pool.
5134          */
5135         int bin = highbit64(BP_GET_PSIZE(bp)) - 1;
5136
5137         zcb->zcb_psize_count[bin]++;
5138         zcb->zcb_psize_len[bin] += BP_GET_PSIZE(bp);
5139         zcb->zcb_psize_total += BP_GET_PSIZE(bp);
5140
5141         bin = highbit64(BP_GET_LSIZE(bp)) - 1;
5142
5143         zcb->zcb_lsize_count[bin]++;
5144         zcb->zcb_lsize_len[bin] += BP_GET_LSIZE(bp);
5145         zcb->zcb_lsize_total += BP_GET_LSIZE(bp);
5146
5147         bin = highbit64(BP_GET_ASIZE(bp)) - 1;
5148
5149         zcb->zcb_asize_count[bin]++;
5150         zcb->zcb_asize_len[bin] += BP_GET_ASIZE(bp);
5151         zcb->zcb_asize_total += BP_GET_ASIZE(bp);
5152
5153         if (dump_opt['L'])
5154                 return;
5155
5156         if (BP_GET_DEDUP(bp)) {
5157                 ddt_t *ddt;
5158                 ddt_entry_t *dde;
5159
5160                 ddt = ddt_select(zcb->zcb_spa, bp);
5161                 ddt_enter(ddt);
5162                 dde = ddt_lookup(ddt, bp, B_FALSE);
5163
5164                 if (dde == NULL) {
5165                         refcnt = 0;
5166                 } else {
5167                         ddt_phys_t *ddp = ddt_phys_select(dde, bp);
5168                         ddt_phys_decref(ddp);
5169                         refcnt = ddp->ddp_refcnt;
5170                         if (ddt_phys_total_refcnt(dde) == 0)
5171                                 ddt_remove(ddt, dde);
5172                 }
5173                 ddt_exit(ddt);
5174         }
5175
5176         VERIFY3U(zio_wait(zio_claim(NULL, zcb->zcb_spa,
5177             refcnt ? 0 : spa_min_claim_txg(zcb->zcb_spa),
5178             bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
5179 }
5180
5181 static void
5182 zdb_blkptr_done(zio_t *zio)
5183 {
5184         spa_t *spa = zio->io_spa;
5185         blkptr_t *bp = zio->io_bp;
5186         int ioerr = zio->io_error;
5187         zdb_cb_t *zcb = zio->io_private;
5188         zbookmark_phys_t *zb = &zio->io_bookmark;
5189
5190         abd_free(zio->io_abd);
5191
5192         mutex_enter(&spa->spa_scrub_lock);
5193         spa->spa_load_verify_bytes -= BP_GET_PSIZE(bp);
5194         cv_broadcast(&spa->spa_scrub_io_cv);
5195
5196         if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
5197                 char blkbuf[BP_SPRINTF_LEN];
5198
5199                 zcb->zcb_haderrors = 1;
5200                 zcb->zcb_errors[ioerr]++;
5201
5202                 if (dump_opt['b'] >= 2)
5203                         snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
5204                 else
5205                         blkbuf[0] = '\0';
5206
5207                 (void) printf("zdb_blkptr_cb: "
5208                     "Got error %d reading "
5209                     "<%llu, %llu, %lld, %llx> %s -- skipping\n",
5210                     ioerr,
5211                     (u_longlong_t)zb->zb_objset,
5212                     (u_longlong_t)zb->zb_object,
5213                     (u_longlong_t)zb->zb_level,
5214                     (u_longlong_t)zb->zb_blkid,
5215                     blkbuf);
5216         }
5217         mutex_exit(&spa->spa_scrub_lock);
5218 }
5219
5220 static int
5221 zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
5222     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
5223 {
5224         zdb_cb_t *zcb = arg;
5225         dmu_object_type_t type;
5226         boolean_t is_metadata;
5227
5228         if (zb->zb_level == ZB_DNODE_LEVEL)
5229                 return (0);
5230
5231         if (dump_opt['b'] >= 5 && bp->blk_birth > 0) {
5232                 char blkbuf[BP_SPRINTF_LEN];
5233                 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
5234                 (void) printf("objset %llu object %llu "
5235                     "level %lld offset 0x%llx %s\n",
5236                     (u_longlong_t)zb->zb_objset,
5237                     (u_longlong_t)zb->zb_object,
5238                     (longlong_t)zb->zb_level,
5239                     (u_longlong_t)blkid2offset(dnp, bp, zb),
5240                     blkbuf);
5241         }
5242
5243         if (BP_IS_HOLE(bp) || BP_IS_REDACTED(bp))
5244                 return (0);
5245
5246         type = BP_GET_TYPE(bp);
5247
5248         zdb_count_block(zcb, zilog, bp,
5249             (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
5250
5251         is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
5252
5253         if (!BP_IS_EMBEDDED(bp) &&
5254             (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata))) {
5255                 size_t size = BP_GET_PSIZE(bp);
5256                 abd_t *abd = abd_alloc(size, B_FALSE);
5257                 int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
5258
5259                 /* If it's an intent log block, failure is expected. */
5260                 if (zb->zb_level == ZB_ZIL_LEVEL)
5261                         flags |= ZIO_FLAG_SPECULATIVE;
5262
5263                 mutex_enter(&spa->spa_scrub_lock);
5264                 while (spa->spa_load_verify_bytes > max_inflight_bytes)
5265                         cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
5266                 spa->spa_load_verify_bytes += size;
5267                 mutex_exit(&spa->spa_scrub_lock);
5268
5269                 zio_nowait(zio_read(NULL, spa, bp, abd, size,
5270                     zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
5271         }
5272
5273         zcb->zcb_readfails = 0;
5274
5275         /* only call gethrtime() every 100 blocks */
5276         static int iters;
5277         if (++iters > 100)
5278                 iters = 0;
5279         else
5280                 return (0);
5281
5282         if (dump_opt['b'] < 5 && gethrtime() > zcb->zcb_lastprint + NANOSEC) {
5283                 uint64_t now = gethrtime();
5284                 char buf[10];
5285                 uint64_t bytes = zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL].zb_asize;
5286                 int kb_per_sec =
5287                     1 + bytes / (1 + ((now - zcb->zcb_start) / 1000 / 1000));
5288                 int sec_remaining =
5289                     (zcb->zcb_totalasize - bytes) / 1024 / kb_per_sec;
5290
5291                 /* make sure nicenum has enough space */
5292                 CTASSERT(sizeof (buf) >= NN_NUMBUF_SZ);
5293
5294                 zfs_nicebytes(bytes, buf, sizeof (buf));
5295                 (void) fprintf(stderr,
5296                     "\r%5s completed (%4dMB/s) "
5297                     "estimated time remaining: %uhr %02umin %02usec        ",
5298                     buf, kb_per_sec / 1024,
5299                     sec_remaining / 60 / 60,
5300                     sec_remaining / 60 % 60,
5301                     sec_remaining % 60);
5302
5303                 zcb->zcb_lastprint = now;
5304         }
5305
5306         return (0);
5307 }
5308
5309 static void
5310 zdb_leak(void *arg, uint64_t start, uint64_t size)
5311 {
5312         vdev_t *vd = arg;
5313
5314         (void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
5315             (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
5316 }
5317
5318 static metaslab_ops_t zdb_metaslab_ops = {
5319         NULL    /* alloc */
5320 };
5321
5322 /* ARGSUSED */
5323 static int
5324 load_unflushed_svr_segs_cb(spa_t *spa, space_map_entry_t *sme,
5325     uint64_t txg, void *arg)
5326 {
5327         spa_vdev_removal_t *svr = arg;
5328
5329         uint64_t offset = sme->sme_offset;
5330         uint64_t size = sme->sme_run;
5331
5332         /* skip vdevs we don't care about */
5333         if (sme->sme_vdev != svr->svr_vdev_id)
5334                 return (0);
5335
5336         vdev_t *vd = vdev_lookup_top(spa, sme->sme_vdev);
5337         metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5338         ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
5339
5340         if (txg < metaslab_unflushed_txg(ms))
5341                 return (0);
5342
5343         vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
5344         ASSERT(vim != NULL);
5345         if (offset >= vdev_indirect_mapping_max_offset(vim))
5346                 return (0);
5347
5348         if (sme->sme_type == SM_ALLOC)
5349                 range_tree_add(svr->svr_allocd_segs, offset, size);
5350         else
5351                 range_tree_remove(svr->svr_allocd_segs, offset, size);
5352
5353         return (0);
5354 }
5355
5356 /* ARGSUSED */
5357 static void
5358 claim_segment_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5359     uint64_t size, void *arg)
5360 {
5361         /*
5362          * This callback was called through a remap from
5363          * a device being removed. Therefore, the vdev that
5364          * this callback is applied to is a concrete
5365          * vdev.
5366          */
5367         ASSERT(vdev_is_concrete(vd));
5368
5369         VERIFY0(metaslab_claim_impl(vd, offset, size,
5370             spa_min_claim_txg(vd->vdev_spa)));
5371 }
5372
5373 static void
5374 claim_segment_cb(void *arg, uint64_t offset, uint64_t size)
5375 {
5376         vdev_t *vd = arg;
5377
5378         vdev_indirect_ops.vdev_op_remap(vd, offset, size,
5379             claim_segment_impl_cb, NULL);
5380 }
5381
5382 /*
5383  * After accounting for all allocated blocks that are directly referenced,
5384  * we might have missed a reference to a block from a partially complete
5385  * (and thus unused) indirect mapping object. We perform a secondary pass
5386  * through the metaslabs we have already mapped and claim the destination
5387  * blocks.
5388  */
5389 static void
5390 zdb_claim_removing(spa_t *spa, zdb_cb_t *zcb)
5391 {
5392         if (dump_opt['L'])
5393                 return;
5394
5395         if (spa->spa_vdev_removal == NULL)
5396                 return;
5397
5398         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5399
5400         spa_vdev_removal_t *svr = spa->spa_vdev_removal;
5401         vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
5402         vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
5403
5404         ASSERT0(range_tree_space(svr->svr_allocd_segs));
5405
5406         range_tree_t *allocs = range_tree_create(NULL, RANGE_SEG64, NULL, 0, 0);
5407         for (uint64_t msi = 0; msi < vd->vdev_ms_count; msi++) {
5408                 metaslab_t *msp = vd->vdev_ms[msi];
5409
5410                 if (msp->ms_start >= vdev_indirect_mapping_max_offset(vim))
5411                         break;
5412
5413                 ASSERT0(range_tree_space(allocs));
5414                 if (msp->ms_sm != NULL)
5415                         VERIFY0(space_map_load(msp->ms_sm, allocs, SM_ALLOC));
5416                 range_tree_vacate(allocs, range_tree_add, svr->svr_allocd_segs);
5417         }
5418         range_tree_destroy(allocs);
5419
5420         iterate_through_spacemap_logs(spa, load_unflushed_svr_segs_cb, svr);
5421
5422         /*
5423          * Clear everything past what has been synced,
5424          * because we have not allocated mappings for
5425          * it yet.
5426          */
5427         range_tree_clear(svr->svr_allocd_segs,
5428             vdev_indirect_mapping_max_offset(vim),
5429             vd->vdev_asize - vdev_indirect_mapping_max_offset(vim));
5430
5431         zcb->zcb_removing_size += range_tree_space(svr->svr_allocd_segs);
5432         range_tree_vacate(svr->svr_allocd_segs, claim_segment_cb, vd);
5433
5434         spa_config_exit(spa, SCL_CONFIG, FTAG);
5435 }
5436
5437 /* ARGSUSED */
5438 static int
5439 increment_indirect_mapping_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
5440     dmu_tx_t *tx)
5441 {
5442         zdb_cb_t *zcb = arg;
5443         spa_t *spa = zcb->zcb_spa;
5444         vdev_t *vd;
5445         const dva_t *dva = &bp->blk_dva[0];
5446
5447         ASSERT(!bp_freed);
5448         ASSERT(!dump_opt['L']);
5449         ASSERT3U(BP_GET_NDVAS(bp), ==, 1);
5450
5451         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
5452         vd = vdev_lookup_top(zcb->zcb_spa, DVA_GET_VDEV(dva));
5453         ASSERT3P(vd, !=, NULL);
5454         spa_config_exit(spa, SCL_VDEV, FTAG);
5455
5456         ASSERT(vd->vdev_indirect_config.vic_mapping_object != 0);
5457         ASSERT3P(zcb->zcb_vd_obsolete_counts[vd->vdev_id], !=, NULL);
5458
5459         vdev_indirect_mapping_increment_obsolete_count(
5460             vd->vdev_indirect_mapping,
5461             DVA_GET_OFFSET(dva), DVA_GET_ASIZE(dva),
5462             zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
5463
5464         return (0);
5465 }
5466
5467 static uint32_t *
5468 zdb_load_obsolete_counts(vdev_t *vd)
5469 {
5470         vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
5471         spa_t *spa = vd->vdev_spa;
5472         spa_condensing_indirect_phys_t *scip =
5473             &spa->spa_condensing_indirect_phys;
5474         uint64_t obsolete_sm_object;
5475         uint32_t *counts;
5476
5477         VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
5478         EQUIV(obsolete_sm_object != 0, vd->vdev_obsolete_sm != NULL);
5479         counts = vdev_indirect_mapping_load_obsolete_counts(vim);
5480         if (vd->vdev_obsolete_sm != NULL) {
5481                 vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
5482                     vd->vdev_obsolete_sm);
5483         }
5484         if (scip->scip_vdev == vd->vdev_id &&
5485             scip->scip_prev_obsolete_sm_object != 0) {
5486                 space_map_t *prev_obsolete_sm = NULL;
5487                 VERIFY0(space_map_open(&prev_obsolete_sm, spa->spa_meta_objset,
5488                     scip->scip_prev_obsolete_sm_object, 0, vd->vdev_asize, 0));
5489                 vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
5490                     prev_obsolete_sm);
5491                 space_map_close(prev_obsolete_sm);
5492         }
5493         return (counts);
5494 }
5495
5496 static void
5497 zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
5498 {
5499         ddt_bookmark_t ddb;
5500         ddt_entry_t dde;
5501         int error;
5502         int p;
5503
5504         ASSERT(!dump_opt['L']);
5505
5506         bzero(&ddb, sizeof (ddb));
5507         while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
5508                 blkptr_t blk;
5509                 ddt_phys_t *ddp = dde.dde_phys;
5510
5511                 if (ddb.ddb_class == DDT_CLASS_UNIQUE)
5512                         return;
5513
5514                 ASSERT(ddt_phys_total_refcnt(&dde) > 1);
5515
5516                 for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
5517                         if (ddp->ddp_phys_birth == 0)
5518                                 continue;
5519                         ddt_bp_create(ddb.ddb_checksum,
5520                             &dde.dde_key, ddp, &blk);
5521                         if (p == DDT_PHYS_DITTO) {
5522                                 zdb_count_block(zcb, NULL, &blk, ZDB_OT_DITTO);
5523                         } else {
5524                                 zcb->zcb_dedup_asize +=
5525                                     BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
5526                                 zcb->zcb_dedup_blocks++;
5527                         }
5528                 }
5529                 ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
5530                 ddt_enter(ddt);
5531                 VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
5532                 ddt_exit(ddt);
5533         }
5534
5535         ASSERT(error == ENOENT);
5536 }
5537
5538 typedef struct checkpoint_sm_exclude_entry_arg {
5539         vdev_t *cseea_vd;
5540         uint64_t cseea_checkpoint_size;
5541 } checkpoint_sm_exclude_entry_arg_t;
5542
5543 static int
5544 checkpoint_sm_exclude_entry_cb(space_map_entry_t *sme, void *arg)
5545 {
5546         checkpoint_sm_exclude_entry_arg_t *cseea = arg;
5547         vdev_t *vd = cseea->cseea_vd;
5548         metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
5549         uint64_t end = sme->sme_offset + sme->sme_run;
5550
5551         ASSERT(sme->sme_type == SM_FREE);
5552
5553         /*
5554          * Since the vdev_checkpoint_sm exists in the vdev level
5555          * and the ms_sm space maps exist in the metaslab level,
5556          * an entry in the checkpoint space map could theoretically
5557          * cross the boundaries of the metaslab that it belongs.
5558          *
5559          * In reality, because of the way that we populate and
5560          * manipulate the checkpoint's space maps currently,
5561          * there shouldn't be any entries that cross metaslabs.
5562          * Hence the assertion below.
5563          *
5564          * That said, there is no fundamental requirement that
5565          * the checkpoint's space map entries should not cross
5566          * metaslab boundaries. So if needed we could add code
5567          * that handles metaslab-crossing segments in the future.
5568          */
5569         VERIFY3U(sme->sme_offset, >=, ms->ms_start);
5570         VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
5571
5572         /*
5573          * By removing the entry from the allocated segments we
5574          * also verify that the entry is there to begin with.
5575          */
5576         mutex_enter(&ms->ms_lock);
5577         range_tree_remove(ms->ms_allocatable, sme->sme_offset, sme->sme_run);
5578         mutex_exit(&ms->ms_lock);
5579
5580         cseea->cseea_checkpoint_size += sme->sme_run;
5581         return (0);
5582 }
5583
5584 static void
5585 zdb_leak_init_vdev_exclude_checkpoint(vdev_t *vd, zdb_cb_t *zcb)
5586 {
5587         spa_t *spa = vd->vdev_spa;
5588         space_map_t *checkpoint_sm = NULL;
5589         uint64_t checkpoint_sm_obj;
5590
5591         /*
5592          * If there is no vdev_top_zap, we are in a pool whose
5593          * version predates the pool checkpoint feature.
5594          */
5595         if (vd->vdev_top_zap == 0)
5596                 return;
5597
5598         /*
5599          * If there is no reference of the vdev_checkpoint_sm in
5600          * the vdev_top_zap, then one of the following scenarios
5601          * is true:
5602          *
5603          * 1] There is no checkpoint
5604          * 2] There is a checkpoint, but no checkpointed blocks
5605          *    have been freed yet
5606          * 3] The current vdev is indirect
5607          *
5608          * In these cases we return immediately.
5609          */
5610         if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
5611             VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
5612                 return;
5613
5614         VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
5615             VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1,
5616             &checkpoint_sm_obj));
5617
5618         checkpoint_sm_exclude_entry_arg_t cseea;
5619         cseea.cseea_vd = vd;
5620         cseea.cseea_checkpoint_size = 0;
5621
5622         VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
5623             checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
5624
5625         VERIFY0(space_map_iterate(checkpoint_sm,
5626             space_map_length(checkpoint_sm),
5627             checkpoint_sm_exclude_entry_cb, &cseea));
5628         space_map_close(checkpoint_sm);
5629
5630         zcb->zcb_checkpoint_size += cseea.cseea_checkpoint_size;
5631 }
5632
5633 static void
5634 zdb_leak_init_exclude_checkpoint(spa_t *spa, zdb_cb_t *zcb)
5635 {
5636         ASSERT(!dump_opt['L']);
5637
5638         vdev_t *rvd = spa->spa_root_vdev;
5639         for (uint64_t c = 0; c < rvd->vdev_children; c++) {
5640                 ASSERT3U(c, ==, rvd->vdev_child[c]->vdev_id);
5641                 zdb_leak_init_vdev_exclude_checkpoint(rvd->vdev_child[c], zcb);
5642         }
5643 }
5644
5645 static int
5646 count_unflushed_space_cb(spa_t *spa, space_map_entry_t *sme,
5647     uint64_t txg, void *arg)
5648 {
5649         int64_t *ualloc_space = arg;
5650
5651         uint64_t offset = sme->sme_offset;
5652         uint64_t vdev_id = sme->sme_vdev;
5653
5654         vdev_t *vd = vdev_lookup_top(spa, vdev_id);
5655         if (!vdev_is_concrete(vd))
5656                 return (0);
5657
5658         metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5659         ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
5660
5661         if (txg < metaslab_unflushed_txg(ms))
5662                 return (0);
5663
5664         if (sme->sme_type == SM_ALLOC)
5665                 *ualloc_space += sme->sme_run;
5666         else
5667                 *ualloc_space -= sme->sme_run;
5668
5669         return (0);
5670 }
5671
5672 static int64_t
5673 get_unflushed_alloc_space(spa_t *spa)
5674 {
5675         if (dump_opt['L'])
5676                 return (0);
5677
5678         int64_t ualloc_space = 0;
5679         iterate_through_spacemap_logs(spa, count_unflushed_space_cb,
5680             &ualloc_space);
5681         return (ualloc_space);
5682 }
5683
5684 static int
5685 load_unflushed_cb(spa_t *spa, space_map_entry_t *sme, uint64_t txg, void *arg)
5686 {
5687         maptype_t *uic_maptype = arg;
5688
5689         uint64_t offset = sme->sme_offset;
5690         uint64_t size = sme->sme_run;
5691         uint64_t vdev_id = sme->sme_vdev;
5692
5693         vdev_t *vd = vdev_lookup_top(spa, vdev_id);
5694
5695         /* skip indirect vdevs */
5696         if (!vdev_is_concrete(vd))
5697                 return (0);
5698
5699         metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5700
5701         ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
5702         ASSERT(*uic_maptype == SM_ALLOC || *uic_maptype == SM_FREE);
5703
5704         if (txg < metaslab_unflushed_txg(ms))
5705                 return (0);
5706
5707         if (*uic_maptype == sme->sme_type)
5708                 range_tree_add(ms->ms_allocatable, offset, size);
5709         else
5710                 range_tree_remove(ms->ms_allocatable, offset, size);
5711
5712         return (0);
5713 }
5714
5715 static void
5716 load_unflushed_to_ms_allocatables(spa_t *spa, maptype_t maptype)
5717 {
5718         iterate_through_spacemap_logs(spa, load_unflushed_cb, &maptype);
5719 }
5720
5721 static void
5722 load_concrete_ms_allocatable_trees(spa_t *spa, maptype_t maptype)
5723 {
5724         vdev_t *rvd = spa->spa_root_vdev;
5725         for (uint64_t i = 0; i < rvd->vdev_children; i++) {
5726                 vdev_t *vd = rvd->vdev_child[i];
5727
5728                 ASSERT3U(i, ==, vd->vdev_id);
5729
5730                 if (vd->vdev_ops == &vdev_indirect_ops)
5731                         continue;
5732
5733                 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
5734                         metaslab_t *msp = vd->vdev_ms[m];
5735
5736                         (void) fprintf(stderr,
5737                             "\rloading concrete vdev %llu, "
5738                             "metaslab %llu of %llu ...",
5739                             (longlong_t)vd->vdev_id,
5740                             (longlong_t)msp->ms_id,
5741                             (longlong_t)vd->vdev_ms_count);
5742
5743                         mutex_enter(&msp->ms_lock);
5744                         range_tree_vacate(msp->ms_allocatable, NULL, NULL);
5745
5746                         /*
5747                          * We don't want to spend the CPU manipulating the
5748                          * size-ordered tree, so clear the range_tree ops.
5749                          */
5750                         msp->ms_allocatable->rt_ops = NULL;
5751
5752                         if (msp->ms_sm != NULL) {
5753                                 VERIFY0(space_map_load(msp->ms_sm,
5754                                     msp->ms_allocatable, maptype));
5755                         }
5756                         if (!msp->ms_loaded)
5757                                 msp->ms_loaded = B_TRUE;
5758                         mutex_exit(&msp->ms_lock);
5759                 }
5760         }
5761
5762         load_unflushed_to_ms_allocatables(spa, maptype);
5763 }
5764
5765 /*
5766  * vm_idxp is an in-out parameter which (for indirect vdevs) is the
5767  * index in vim_entries that has the first entry in this metaslab.
5768  * On return, it will be set to the first entry after this metaslab.
5769  */
5770 static void
5771 load_indirect_ms_allocatable_tree(vdev_t *vd, metaslab_t *msp,
5772     uint64_t *vim_idxp)
5773 {
5774         vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
5775
5776         mutex_enter(&msp->ms_lock);
5777         range_tree_vacate(msp->ms_allocatable, NULL, NULL);
5778
5779         /*
5780          * We don't want to spend the CPU manipulating the
5781          * size-ordered tree, so clear the range_tree ops.
5782          */
5783         msp->ms_allocatable->rt_ops = NULL;
5784
5785         for (; *vim_idxp < vdev_indirect_mapping_num_entries(vim);
5786             (*vim_idxp)++) {
5787                 vdev_indirect_mapping_entry_phys_t *vimep =
5788                     &vim->vim_entries[*vim_idxp];
5789                 uint64_t ent_offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
5790                 uint64_t ent_len = DVA_GET_ASIZE(&vimep->vimep_dst);
5791                 ASSERT3U(ent_offset, >=, msp->ms_start);
5792                 if (ent_offset >= msp->ms_start + msp->ms_size)
5793                         break;
5794
5795                 /*
5796                  * Mappings do not cross metaslab boundaries,
5797                  * because we create them by walking the metaslabs.
5798                  */
5799                 ASSERT3U(ent_offset + ent_len, <=,
5800                     msp->ms_start + msp->ms_size);
5801                 range_tree_add(msp->ms_allocatable, ent_offset, ent_len);
5802         }
5803
5804         if (!msp->ms_loaded)
5805                 msp->ms_loaded = B_TRUE;
5806         mutex_exit(&msp->ms_lock);
5807 }
5808
5809 static void
5810 zdb_leak_init_prepare_indirect_vdevs(spa_t *spa, zdb_cb_t *zcb)
5811 {
5812         ASSERT(!dump_opt['L']);
5813
5814         vdev_t *rvd = spa->spa_root_vdev;
5815         for (uint64_t c = 0; c < rvd->vdev_children; c++) {
5816                 vdev_t *vd = rvd->vdev_child[c];
5817
5818                 ASSERT3U(c, ==, vd->vdev_id);
5819
5820                 if (vd->vdev_ops != &vdev_indirect_ops)
5821                         continue;
5822
5823                 /*
5824                  * Note: we don't check for mapping leaks on
5825                  * removing vdevs because their ms_allocatable's
5826                  * are used to look for leaks in allocated space.
5827                  */
5828                 zcb->zcb_vd_obsolete_counts[c] = zdb_load_obsolete_counts(vd);
5829
5830                 /*
5831                  * Normally, indirect vdevs don't have any
5832                  * metaslabs.  We want to set them up for
5833                  * zio_claim().
5834                  */
5835                 VERIFY0(vdev_metaslab_init(vd, 0));
5836
5837                 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
5838                 uint64_t vim_idx = 0;
5839                 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
5840
5841                         (void) fprintf(stderr,
5842                             "\rloading indirect vdev %llu, "
5843                             "metaslab %llu of %llu ...",
5844                             (longlong_t)vd->vdev_id,
5845                             (longlong_t)vd->vdev_ms[m]->ms_id,
5846                             (longlong_t)vd->vdev_ms_count);
5847
5848                         load_indirect_ms_allocatable_tree(vd, vd->vdev_ms[m],
5849                             &vim_idx);
5850                 }
5851                 ASSERT3U(vim_idx, ==, vdev_indirect_mapping_num_entries(vim));
5852         }
5853 }
5854
5855 static void
5856 zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
5857 {
5858         zcb->zcb_spa = spa;
5859
5860         if (dump_opt['L'])
5861                 return;
5862
5863         dsl_pool_t *dp = spa->spa_dsl_pool;
5864         vdev_t *rvd = spa->spa_root_vdev;
5865
5866         /*
5867          * We are going to be changing the meaning of the metaslab's
5868          * ms_allocatable.  Ensure that the allocator doesn't try to
5869          * use the tree.
5870          */
5871         spa->spa_normal_class->mc_ops = &zdb_metaslab_ops;
5872         spa->spa_log_class->mc_ops = &zdb_metaslab_ops;
5873
5874         zcb->zcb_vd_obsolete_counts =
5875             umem_zalloc(rvd->vdev_children * sizeof (uint32_t *),
5876             UMEM_NOFAIL);
5877
5878         /*
5879          * For leak detection, we overload the ms_allocatable trees
5880          * to contain allocated segments instead of free segments.
5881          * As a result, we can't use the normal metaslab_load/unload
5882          * interfaces.
5883          */
5884         zdb_leak_init_prepare_indirect_vdevs(spa, zcb);
5885         load_concrete_ms_allocatable_trees(spa, SM_ALLOC);
5886
5887         /*
5888          * On load_concrete_ms_allocatable_trees() we loaded all the
5889          * allocated entries from the ms_sm to the ms_allocatable for
5890          * each metaslab. If the pool has a checkpoint or is in the
5891          * middle of discarding a checkpoint, some of these blocks
5892          * may have been freed but their ms_sm may not have been
5893          * updated because they are referenced by the checkpoint. In
5894          * order to avoid false-positives during leak-detection, we
5895          * go through the vdev's checkpoint space map and exclude all
5896          * its entries from their relevant ms_allocatable.
5897          *
5898          * We also aggregate the space held by the checkpoint and add
5899          * it to zcb_checkpoint_size.
5900          *
5901          * Note that at this point we are also verifying that all the
5902          * entries on the checkpoint_sm are marked as allocated in
5903          * the ms_sm of their relevant metaslab.
5904          * [see comment in checkpoint_sm_exclude_entry_cb()]
5905          */
5906         zdb_leak_init_exclude_checkpoint(spa, zcb);
5907         ASSERT3U(zcb->zcb_checkpoint_size, ==, spa_get_checkpoint_space(spa));
5908
5909         /* for cleaner progress output */
5910         (void) fprintf(stderr, "\n");
5911
5912         if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
5913                 ASSERT(spa_feature_is_enabled(spa,
5914                     SPA_FEATURE_DEVICE_REMOVAL));
5915                 (void) bpobj_iterate_nofree(&dp->dp_obsolete_bpobj,
5916                     increment_indirect_mapping_cb, zcb, NULL);
5917         }
5918
5919         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5920         zdb_ddt_leak_init(spa, zcb);
5921         spa_config_exit(spa, SCL_CONFIG, FTAG);
5922 }
5923
5924 static boolean_t
5925 zdb_check_for_obsolete_leaks(vdev_t *vd, zdb_cb_t *zcb)
5926 {
5927         boolean_t leaks = B_FALSE;
5928         vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
5929         uint64_t total_leaked = 0;
5930         boolean_t are_precise = B_FALSE;
5931
5932         ASSERT(vim != NULL);
5933
5934         for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
5935                 vdev_indirect_mapping_entry_phys_t *vimep =
5936                     &vim->vim_entries[i];
5937                 uint64_t obsolete_bytes = 0;
5938                 uint64_t offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
5939                 metaslab_t *msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5940
5941                 /*
5942                  * This is not very efficient but it's easy to
5943                  * verify correctness.
5944                  */
5945                 for (uint64_t inner_offset = 0;
5946                     inner_offset < DVA_GET_ASIZE(&vimep->vimep_dst);
5947                     inner_offset += 1 << vd->vdev_ashift) {
5948                         if (range_tree_contains(msp->ms_allocatable,
5949                             offset + inner_offset, 1 << vd->vdev_ashift)) {
5950                                 obsolete_bytes += 1 << vd->vdev_ashift;
5951                         }
5952                 }
5953
5954                 int64_t bytes_leaked = obsolete_bytes -
5955                     zcb->zcb_vd_obsolete_counts[vd->vdev_id][i];
5956                 ASSERT3U(DVA_GET_ASIZE(&vimep->vimep_dst), >=,
5957                     zcb->zcb_vd_obsolete_counts[vd->vdev_id][i]);
5958
5959                 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
5960                 if (bytes_leaked != 0 && (are_precise || dump_opt['d'] >= 5)) {
5961                         (void) printf("obsolete indirect mapping count "
5962                             "mismatch on %llu:%llx:%llx : %llx bytes leaked\n",
5963                             (u_longlong_t)vd->vdev_id,
5964                             (u_longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
5965                             (u_longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
5966                             (u_longlong_t)bytes_leaked);
5967                 }
5968                 total_leaked += ABS(bytes_leaked);
5969         }
5970
5971         VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
5972         if (!are_precise && total_leaked > 0) {
5973                 int pct_leaked = total_leaked * 100 /
5974                     vdev_indirect_mapping_bytes_mapped(vim);
5975                 (void) printf("cannot verify obsolete indirect mapping "
5976                     "counts of vdev %llu because precise feature was not "
5977                     "enabled when it was removed: %d%% (%llx bytes) of mapping"
5978                     "unreferenced\n",
5979                     (u_longlong_t)vd->vdev_id, pct_leaked,
5980                     (u_longlong_t)total_leaked);
5981         } else if (total_leaked > 0) {
5982                 (void) printf("obsolete indirect mapping count mismatch "
5983                     "for vdev %llu -- %llx total bytes mismatched\n",
5984                     (u_longlong_t)vd->vdev_id,
5985                     (u_longlong_t)total_leaked);
5986                 leaks |= B_TRUE;
5987         }
5988
5989         vdev_indirect_mapping_free_obsolete_counts(vim,
5990             zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
5991         zcb->zcb_vd_obsolete_counts[vd->vdev_id] = NULL;
5992
5993         return (leaks);
5994 }
5995
5996 static boolean_t
5997 zdb_leak_fini(spa_t *spa, zdb_cb_t *zcb)
5998 {
5999         if (dump_opt['L'])
6000                 return (B_FALSE);
6001
6002         boolean_t leaks = B_FALSE;
6003         vdev_t *rvd = spa->spa_root_vdev;
6004         for (unsigned c = 0; c < rvd->vdev_children; c++) {
6005                 vdev_t *vd = rvd->vdev_child[c];
6006                 metaslab_group_t *mg __maybe_unused = vd->vdev_mg;
6007
6008                 if (zcb->zcb_vd_obsolete_counts[c] != NULL) {
6009                         leaks |= zdb_check_for_obsolete_leaks(vd, zcb);
6010                 }
6011
6012                 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
6013                         metaslab_t *msp = vd->vdev_ms[m];
6014                         ASSERT3P(mg, ==, msp->ms_group);
6015
6016                         /*
6017                          * ms_allocatable has been overloaded
6018                          * to contain allocated segments. Now that
6019                          * we finished traversing all blocks, any
6020                          * block that remains in the ms_allocatable
6021                          * represents an allocated block that we
6022                          * did not claim during the traversal.
6023                          * Claimed blocks would have been removed
6024                          * from the ms_allocatable.  For indirect
6025                          * vdevs, space remaining in the tree
6026                          * represents parts of the mapping that are
6027                          * not referenced, which is not a bug.
6028                          */
6029                         if (vd->vdev_ops == &vdev_indirect_ops) {
6030                                 range_tree_vacate(msp->ms_allocatable,
6031                                     NULL, NULL);
6032                         } else {
6033                                 range_tree_vacate(msp->ms_allocatable,
6034                                     zdb_leak, vd);
6035                         }
6036                         if (msp->ms_loaded) {
6037                                 msp->ms_loaded = B_FALSE;
6038                         }
6039                 }
6040         }
6041
6042         umem_free(zcb->zcb_vd_obsolete_counts,
6043             rvd->vdev_children * sizeof (uint32_t *));
6044         zcb->zcb_vd_obsolete_counts = NULL;
6045
6046         return (leaks);
6047 }
6048
6049 /* ARGSUSED */
6050 static int
6051 count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
6052 {
6053         zdb_cb_t *zcb = arg;
6054
6055         if (dump_opt['b'] >= 5) {
6056                 char blkbuf[BP_SPRINTF_LEN];
6057                 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
6058                 (void) printf("[%s] %s\n",
6059                     "deferred free", blkbuf);
6060         }
6061         zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
6062         return (0);
6063 }
6064
6065 /*
6066  * Iterate over livelists which have been destroyed by the user but
6067  * are still present in the MOS, waiting to be freed
6068  */
6069 static void
6070 iterate_deleted_livelists(spa_t *spa, ll_iter_t func, void *arg)
6071 {
6072         objset_t *mos = spa->spa_meta_objset;
6073         uint64_t zap_obj;
6074         int err = zap_lookup(mos, DMU_POOL_DIRECTORY_OBJECT,
6075             DMU_POOL_DELETED_CLONES, sizeof (uint64_t), 1, &zap_obj);
6076         if (err == ENOENT)
6077                 return;
6078         ASSERT0(err);
6079
6080         zap_cursor_t zc;
6081         zap_attribute_t attr;
6082         dsl_deadlist_t ll;
6083         /* NULL out os prior to dsl_deadlist_open in case it's garbage */
6084         ll.dl_os = NULL;
6085         for (zap_cursor_init(&zc, mos, zap_obj);
6086             zap_cursor_retrieve(&zc, &attr) == 0;
6087             (void) zap_cursor_advance(&zc)) {
6088                 dsl_deadlist_open(&ll, mos, attr.za_first_integer);
6089                 func(&ll, arg);
6090                 dsl_deadlist_close(&ll);
6091         }
6092         zap_cursor_fini(&zc);
6093 }
6094
6095 static int
6096 bpobj_count_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
6097     dmu_tx_t *tx)
6098 {
6099         ASSERT(!bp_freed);
6100         return (count_block_cb(arg, bp, tx));
6101 }
6102
6103 static int
6104 livelist_entry_count_blocks_cb(void *args, dsl_deadlist_entry_t *dle)
6105 {
6106         zdb_cb_t *zbc = args;
6107         bplist_t blks;
6108         bplist_create(&blks);
6109         /* determine which blocks have been alloc'd but not freed */
6110         VERIFY0(dsl_process_sub_livelist(&dle->dle_bpobj, &blks, NULL, NULL));
6111         /* count those blocks */
6112         (void) bplist_iterate(&blks, count_block_cb, zbc, NULL);
6113         bplist_destroy(&blks);
6114         return (0);
6115 }
6116
6117 static void
6118 livelist_count_blocks(dsl_deadlist_t *ll, void *arg)
6119 {
6120         dsl_deadlist_iterate(ll, livelist_entry_count_blocks_cb, arg);
6121 }
6122
6123 /*
6124  * Count the blocks in the livelists that have been destroyed by the user
6125  * but haven't yet been freed.
6126  */
6127 static void
6128 deleted_livelists_count_blocks(spa_t *spa, zdb_cb_t *zbc)
6129 {
6130         iterate_deleted_livelists(spa, livelist_count_blocks, zbc);
6131 }
6132
6133 static void
6134 dump_livelist_cb(dsl_deadlist_t *ll, void *arg)
6135 {
6136         ASSERT3P(arg, ==, NULL);
6137         global_feature_count[SPA_FEATURE_LIVELIST]++;
6138         dump_blkptr_list(ll, "Deleted Livelist");
6139         dsl_deadlist_iterate(ll, sublivelist_verify_lightweight, NULL);
6140 }
6141
6142 /*
6143  * Print out, register object references to, and increment feature counts for
6144  * livelists that have been destroyed by the user but haven't yet been freed.
6145  */
6146 static void
6147 deleted_livelists_dump_mos(spa_t *spa)
6148 {
6149         uint64_t zap_obj;
6150         objset_t *mos = spa->spa_meta_objset;
6151         int err = zap_lookup(mos, DMU_POOL_DIRECTORY_OBJECT,
6152             DMU_POOL_DELETED_CLONES, sizeof (uint64_t), 1, &zap_obj);
6153         if (err == ENOENT)
6154                 return;
6155         mos_obj_refd(zap_obj);
6156         iterate_deleted_livelists(spa, dump_livelist_cb, NULL);
6157 }
6158
6159 static int
6160 dump_block_stats(spa_t *spa)
6161 {
6162         zdb_cb_t zcb;
6163         zdb_blkstats_t *zb, *tzb;
6164         uint64_t norm_alloc, norm_space, total_alloc, total_found;
6165         int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
6166             TRAVERSE_NO_DECRYPT | TRAVERSE_HARD;
6167         boolean_t leaks = B_FALSE;
6168         int e, c, err;
6169         bp_embedded_type_t i;
6170
6171         bzero(&zcb, sizeof (zcb));
6172         (void) printf("\nTraversing all blocks %s%s%s%s%s...\n\n",
6173             (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
6174             (dump_opt['c'] == 1) ? "metadata " : "",
6175             dump_opt['c'] ? "checksums " : "",
6176             (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
6177             !dump_opt['L'] ? "nothing leaked " : "");
6178
6179         /*
6180          * When leak detection is enabled we load all space maps as SM_ALLOC
6181          * maps, then traverse the pool claiming each block we discover. If
6182          * the pool is perfectly consistent, the segment trees will be empty
6183          * when we're done. Anything left over is a leak; any block we can't
6184          * claim (because it's not part of any space map) is a double
6185          * allocation, reference to a freed block, or an unclaimed log block.
6186          *
6187          * When leak detection is disabled (-L option) we still traverse the
6188          * pool claiming each block we discover, but we skip opening any space
6189          * maps.
6190          */
6191         bzero(&zcb, sizeof (zdb_cb_t));
6192         zdb_leak_init(spa, &zcb);
6193
6194         /*
6195          * If there's a deferred-free bplist, process that first.
6196          */
6197         (void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
6198             bpobj_count_block_cb, &zcb, NULL);
6199
6200         if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
6201                 (void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
6202                     bpobj_count_block_cb, &zcb, NULL);
6203         }
6204
6205         zdb_claim_removing(spa, &zcb);
6206
6207         if (spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
6208                 VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
6209                     spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
6210                     &zcb, NULL));
6211         }
6212
6213         deleted_livelists_count_blocks(spa, &zcb);
6214
6215         if (dump_opt['c'] > 1)
6216                 flags |= TRAVERSE_PREFETCH_DATA;
6217
6218         zcb.zcb_totalasize = metaslab_class_get_alloc(spa_normal_class(spa));
6219         zcb.zcb_totalasize += metaslab_class_get_alloc(spa_special_class(spa));
6220         zcb.zcb_totalasize += metaslab_class_get_alloc(spa_dedup_class(spa));
6221         zcb.zcb_start = zcb.zcb_lastprint = gethrtime();
6222         err = traverse_pool(spa, 0, flags, zdb_blkptr_cb, &zcb);
6223
6224         /*
6225          * If we've traversed the data blocks then we need to wait for those
6226          * I/Os to complete. We leverage "The Godfather" zio to wait on
6227          * all async I/Os to complete.
6228          */
6229         if (dump_opt['c']) {
6230                 for (c = 0; c < max_ncpus; c++) {
6231                         (void) zio_wait(spa->spa_async_zio_root[c]);
6232                         spa->spa_async_zio_root[c] = zio_root(spa, NULL, NULL,
6233                             ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
6234                             ZIO_FLAG_GODFATHER);
6235                 }
6236         }
6237         ASSERT0(spa->spa_load_verify_bytes);
6238
6239         /*
6240          * Done after zio_wait() since zcb_haderrors is modified in
6241          * zdb_blkptr_done()
6242          */
6243         zcb.zcb_haderrors |= err;
6244
6245         if (zcb.zcb_haderrors) {
6246                 (void) printf("\nError counts:\n\n");
6247                 (void) printf("\t%5s  %s\n", "errno", "count");
6248                 for (e = 0; e < 256; e++) {
6249                         if (zcb.zcb_errors[e] != 0) {
6250                                 (void) printf("\t%5d  %llu\n",
6251                                     e, (u_longlong_t)zcb.zcb_errors[e]);
6252                         }
6253                 }
6254         }
6255
6256         /*
6257          * Report any leaked segments.
6258          */
6259         leaks |= zdb_leak_fini(spa, &zcb);
6260
6261         tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
6262
6263         norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
6264         norm_space = metaslab_class_get_space(spa_normal_class(spa));
6265
6266         total_alloc = norm_alloc +
6267             metaslab_class_get_alloc(spa_log_class(spa)) +
6268             metaslab_class_get_alloc(spa_special_class(spa)) +
6269             metaslab_class_get_alloc(spa_dedup_class(spa)) +
6270             get_unflushed_alloc_space(spa);
6271         total_found = tzb->zb_asize - zcb.zcb_dedup_asize +
6272             zcb.zcb_removing_size + zcb.zcb_checkpoint_size;
6273
6274         if (total_found == total_alloc && !dump_opt['L']) {
6275                 (void) printf("\n\tNo leaks (block sum matches space"
6276                     " maps exactly)\n");
6277         } else if (!dump_opt['L']) {
6278                 (void) printf("block traversal size %llu != alloc %llu "
6279                     "(%s %lld)\n",
6280                     (u_longlong_t)total_found,
6281                     (u_longlong_t)total_alloc,
6282                     (dump_opt['L']) ? "unreachable" : "leaked",
6283                     (longlong_t)(total_alloc - total_found));
6284                 leaks = B_TRUE;
6285         }
6286
6287         if (tzb->zb_count == 0)
6288                 return (2);
6289
6290         (void) printf("\n");
6291         (void) printf("\t%-16s %14llu\n", "bp count:",
6292             (u_longlong_t)tzb->zb_count);
6293         (void) printf("\t%-16s %14llu\n", "ganged count:",
6294             (longlong_t)tzb->zb_gangs);
6295         (void) printf("\t%-16s %14llu      avg: %6llu\n", "bp logical:",
6296             (u_longlong_t)tzb->zb_lsize,
6297             (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
6298         (void) printf("\t%-16s %14llu      avg: %6llu     compression: %6.2f\n",
6299             "bp physical:", (u_longlong_t)tzb->zb_psize,
6300             (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
6301             (double)tzb->zb_lsize / tzb->zb_psize);
6302         (void) printf("\t%-16s %14llu      avg: %6llu     compression: %6.2f\n",
6303             "bp allocated:", (u_longlong_t)tzb->zb_asize,
6304             (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
6305             (double)tzb->zb_lsize / tzb->zb_asize);
6306         (void) printf("\t%-16s %14llu    ref>1: %6llu   deduplication: %6.2f\n",
6307             "bp deduped:", (u_longlong_t)zcb.zcb_dedup_asize,
6308             (u_longlong_t)zcb.zcb_dedup_blocks,
6309             (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
6310         (void) printf("\t%-16s %14llu     used: %5.2f%%\n", "Normal class:",
6311             (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
6312
6313         if (spa_special_class(spa)->mc_rotor != NULL) {
6314                 uint64_t alloc = metaslab_class_get_alloc(
6315                     spa_special_class(spa));
6316                 uint64_t space = metaslab_class_get_space(
6317                     spa_special_class(spa));
6318
6319                 (void) printf("\t%-16s %14llu     used: %5.2f%%\n",
6320                     "Special class", (u_longlong_t)alloc,
6321                     100.0 * alloc / space);
6322         }
6323
6324         if (spa_dedup_class(spa)->mc_rotor != NULL) {
6325                 uint64_t alloc = metaslab_class_get_alloc(
6326                     spa_dedup_class(spa));
6327                 uint64_t space = metaslab_class_get_space(
6328                     spa_dedup_class(spa));
6329
6330                 (void) printf("\t%-16s %14llu     used: %5.2f%%\n",
6331                     "Dedup class", (u_longlong_t)alloc,
6332                     100.0 * alloc / space);
6333         }
6334
6335         for (i = 0; i < NUM_BP_EMBEDDED_TYPES; i++) {
6336                 if (zcb.zcb_embedded_blocks[i] == 0)
6337                         continue;
6338                 (void) printf("\n");
6339                 (void) printf("\tadditional, non-pointer bps of type %u: "
6340                     "%10llu\n",
6341                     i, (u_longlong_t)zcb.zcb_embedded_blocks[i]);
6342
6343                 if (dump_opt['b'] >= 3) {
6344                         (void) printf("\t number of (compressed) bytes:  "
6345                             "number of bps\n");
6346                         dump_histogram(zcb.zcb_embedded_histogram[i],
6347                             sizeof (zcb.zcb_embedded_histogram[i]) /
6348                             sizeof (zcb.zcb_embedded_histogram[i][0]), 0);
6349                 }
6350         }
6351
6352         if (tzb->zb_ditto_samevdev != 0) {
6353                 (void) printf("\tDittoed blocks on same vdev: %llu\n",
6354                     (longlong_t)tzb->zb_ditto_samevdev);
6355         }
6356         if (tzb->zb_ditto_same_ms != 0) {
6357                 (void) printf("\tDittoed blocks in same metaslab: %llu\n",
6358                     (longlong_t)tzb->zb_ditto_same_ms);
6359         }
6360
6361         for (uint64_t v = 0; v < spa->spa_root_vdev->vdev_children; v++) {
6362                 vdev_t *vd = spa->spa_root_vdev->vdev_child[v];
6363                 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6364
6365                 if (vim == NULL) {
6366                         continue;
6367                 }
6368
6369                 char mem[32];
6370                 zdb_nicenum(vdev_indirect_mapping_num_entries(vim),
6371                     mem, vdev_indirect_mapping_size(vim));
6372
6373                 (void) printf("\tindirect vdev id %llu has %llu segments "
6374                     "(%s in memory)\n",
6375                     (longlong_t)vd->vdev_id,
6376                     (longlong_t)vdev_indirect_mapping_num_entries(vim), mem);
6377         }
6378
6379         if (dump_opt['b'] >= 2) {
6380                 int l, t, level;
6381                 (void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
6382                     "\t  avg\t comp\t%%Total\tType\n");
6383
6384                 for (t = 0; t <= ZDB_OT_TOTAL; t++) {
6385                         char csize[32], lsize[32], psize[32], asize[32];
6386                         char avg[32], gang[32];
6387                         const char *typename;
6388
6389                         /* make sure nicenum has enough space */
6390                         CTASSERT(sizeof (csize) >= NN_NUMBUF_SZ);
6391                         CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
6392                         CTASSERT(sizeof (psize) >= NN_NUMBUF_SZ);
6393                         CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
6394                         CTASSERT(sizeof (avg) >= NN_NUMBUF_SZ);
6395                         CTASSERT(sizeof (gang) >= NN_NUMBUF_SZ);
6396
6397                         if (t < DMU_OT_NUMTYPES)
6398                                 typename = dmu_ot[t].ot_name;
6399                         else
6400                                 typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
6401
6402                         if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
6403                                 (void) printf("%6s\t%5s\t%5s\t%5s"
6404                                     "\t%5s\t%5s\t%6s\t%s\n",
6405                                     "-",
6406                                     "-",
6407                                     "-",
6408                                     "-",
6409                                     "-",
6410                                     "-",
6411                                     "-",
6412                                     typename);
6413                                 continue;
6414                         }
6415
6416                         for (l = ZB_TOTAL - 1; l >= -1; l--) {
6417                                 level = (l == -1 ? ZB_TOTAL : l);
6418                                 zb = &zcb.zcb_type[level][t];
6419
6420                                 if (zb->zb_asize == 0)
6421                                         continue;
6422
6423                                 if (dump_opt['b'] < 3 && level != ZB_TOTAL)
6424                                         continue;
6425
6426                                 if (level == 0 && zb->zb_asize ==
6427                                     zcb.zcb_type[ZB_TOTAL][t].zb_asize)
6428                                         continue;
6429
6430                                 zdb_nicenum(zb->zb_count, csize,
6431                                     sizeof (csize));
6432                                 zdb_nicenum(zb->zb_lsize, lsize,
6433                                     sizeof (lsize));
6434                                 zdb_nicenum(zb->zb_psize, psize,
6435                                     sizeof (psize));
6436                                 zdb_nicenum(zb->zb_asize, asize,
6437                                     sizeof (asize));
6438                                 zdb_nicenum(zb->zb_asize / zb->zb_count, avg,
6439                                     sizeof (avg));
6440                                 zdb_nicenum(zb->zb_gangs, gang, sizeof (gang));
6441
6442                                 (void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
6443                                     "\t%5.2f\t%6.2f\t",
6444                                     csize, lsize, psize, asize, avg,
6445                                     (double)zb->zb_lsize / zb->zb_psize,
6446                                     100.0 * zb->zb_asize / tzb->zb_asize);
6447
6448                                 if (level == ZB_TOTAL)
6449                                         (void) printf("%s\n", typename);
6450                                 else
6451                                         (void) printf("    L%d %s\n",
6452                                             level, typename);
6453
6454                                 if (dump_opt['b'] >= 3 && zb->zb_gangs > 0) {
6455                                         (void) printf("\t number of ganged "
6456                                             "blocks: %s\n", gang);
6457                                 }
6458
6459                                 if (dump_opt['b'] >= 4) {
6460                                         (void) printf("psize "
6461                                             "(in 512-byte sectors): "
6462                                             "number of blocks\n");
6463                                         dump_histogram(zb->zb_psize_histogram,
6464                                             PSIZE_HISTO_SIZE, 0);
6465                                 }
6466                         }
6467                 }
6468
6469                 /* Output a table summarizing block sizes in the pool */
6470                 if (dump_opt['b'] >= 2) {
6471                         dump_size_histograms(&zcb);
6472                 }
6473         }
6474
6475         (void) printf("\n");
6476
6477         if (leaks)
6478                 return (2);
6479
6480         if (zcb.zcb_haderrors)
6481                 return (3);
6482
6483         return (0);
6484 }
6485
6486 typedef struct zdb_ddt_entry {
6487         ddt_key_t       zdde_key;
6488         uint64_t        zdde_ref_blocks;
6489         uint64_t        zdde_ref_lsize;
6490         uint64_t        zdde_ref_psize;
6491         uint64_t        zdde_ref_dsize;
6492         avl_node_t      zdde_node;
6493 } zdb_ddt_entry_t;
6494
6495 /* ARGSUSED */
6496 static int
6497 zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
6498     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
6499 {
6500         avl_tree_t *t = arg;
6501         avl_index_t where;
6502         zdb_ddt_entry_t *zdde, zdde_search;
6503
6504         if (zb->zb_level == ZB_DNODE_LEVEL || BP_IS_HOLE(bp) ||
6505             BP_IS_EMBEDDED(bp))
6506                 return (0);
6507
6508         if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
6509                 (void) printf("traversing objset %llu, %llu objects, "
6510                     "%lu blocks so far\n",
6511                     (u_longlong_t)zb->zb_objset,
6512                     (u_longlong_t)BP_GET_FILL(bp),
6513                     avl_numnodes(t));
6514         }
6515
6516         if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
6517             BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
6518                 return (0);
6519
6520         ddt_key_fill(&zdde_search.zdde_key, bp);
6521
6522         zdde = avl_find(t, &zdde_search, &where);
6523
6524         if (zdde == NULL) {
6525                 zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
6526                 zdde->zdde_key = zdde_search.zdde_key;
6527                 avl_insert(t, zdde, where);
6528         }
6529
6530         zdde->zdde_ref_blocks += 1;
6531         zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
6532         zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
6533         zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
6534
6535         return (0);
6536 }
6537
6538 static void
6539 dump_simulated_ddt(spa_t *spa)
6540 {
6541         avl_tree_t t;
6542         void *cookie = NULL;
6543         zdb_ddt_entry_t *zdde;
6544         ddt_histogram_t ddh_total;
6545         ddt_stat_t dds_total;
6546
6547         bzero(&ddh_total, sizeof (ddh_total));
6548         bzero(&dds_total, sizeof (dds_total));
6549         avl_create(&t, ddt_entry_compare,
6550             sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
6551
6552         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6553
6554         (void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
6555             TRAVERSE_NO_DECRYPT, zdb_ddt_add_cb, &t);
6556
6557         spa_config_exit(spa, SCL_CONFIG, FTAG);
6558
6559         while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
6560                 ddt_stat_t dds;
6561                 uint64_t refcnt = zdde->zdde_ref_blocks;
6562                 ASSERT(refcnt != 0);
6563
6564                 dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
6565                 dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
6566                 dds.dds_psize = zdde->zdde_ref_psize / refcnt;
6567                 dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
6568
6569                 dds.dds_ref_blocks = zdde->zdde_ref_blocks;
6570                 dds.dds_ref_lsize = zdde->zdde_ref_lsize;
6571                 dds.dds_ref_psize = zdde->zdde_ref_psize;
6572                 dds.dds_ref_dsize = zdde->zdde_ref_dsize;
6573
6574                 ddt_stat_add(&ddh_total.ddh_stat[highbit64(refcnt) - 1],
6575                     &dds, 0);
6576
6577                 umem_free(zdde, sizeof (*zdde));
6578         }
6579
6580         avl_destroy(&t);
6581
6582         ddt_histogram_stat(&dds_total, &ddh_total);
6583
6584         (void) printf("Simulated DDT histogram:\n");
6585
6586         zpool_dump_ddt(&dds_total, &ddh_total);
6587
6588         dump_dedup_ratio(&dds_total);
6589 }
6590
6591 static int
6592 verify_device_removal_feature_counts(spa_t *spa)
6593 {
6594         uint64_t dr_feature_refcount = 0;
6595         uint64_t oc_feature_refcount = 0;
6596         uint64_t indirect_vdev_count = 0;
6597         uint64_t precise_vdev_count = 0;
6598         uint64_t obsolete_counts_object_count = 0;
6599         uint64_t obsolete_sm_count = 0;
6600         uint64_t obsolete_counts_count = 0;
6601         uint64_t scip_count = 0;
6602         uint64_t obsolete_bpobj_count = 0;
6603         int ret = 0;
6604
6605         spa_condensing_indirect_phys_t *scip =
6606             &spa->spa_condensing_indirect_phys;
6607         if (scip->scip_next_mapping_object != 0) {
6608                 vdev_t *vd = spa->spa_root_vdev->vdev_child[scip->scip_vdev];
6609                 ASSERT(scip->scip_prev_obsolete_sm_object != 0);
6610                 ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
6611
6612                 (void) printf("Condensing indirect vdev %llu: new mapping "
6613                     "object %llu, prev obsolete sm %llu\n",
6614                     (u_longlong_t)scip->scip_vdev,
6615                     (u_longlong_t)scip->scip_next_mapping_object,
6616                     (u_longlong_t)scip->scip_prev_obsolete_sm_object);
6617                 if (scip->scip_prev_obsolete_sm_object != 0) {
6618                         space_map_t *prev_obsolete_sm = NULL;
6619                         VERIFY0(space_map_open(&prev_obsolete_sm,
6620                             spa->spa_meta_objset,
6621                             scip->scip_prev_obsolete_sm_object,
6622                             0, vd->vdev_asize, 0));
6623                         dump_spacemap(spa->spa_meta_objset, prev_obsolete_sm);
6624                         (void) printf("\n");
6625                         space_map_close(prev_obsolete_sm);
6626                 }
6627
6628                 scip_count += 2;
6629         }
6630
6631         for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
6632                 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
6633                 vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
6634
6635                 if (vic->vic_mapping_object != 0) {
6636                         ASSERT(vd->vdev_ops == &vdev_indirect_ops ||
6637                             vd->vdev_removing);
6638                         indirect_vdev_count++;
6639
6640                         if (vd->vdev_indirect_mapping->vim_havecounts) {
6641                                 obsolete_counts_count++;
6642                         }
6643                 }
6644
6645                 boolean_t are_precise;
6646                 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
6647                 if (are_precise) {
6648                         ASSERT(vic->vic_mapping_object != 0);
6649                         precise_vdev_count++;
6650                 }
6651
6652                 uint64_t obsolete_sm_object;
6653                 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
6654                 if (obsolete_sm_object != 0) {
6655                         ASSERT(vic->vic_mapping_object != 0);
6656                         obsolete_sm_count++;
6657                 }
6658         }
6659
6660         (void) feature_get_refcount(spa,
6661             &spa_feature_table[SPA_FEATURE_DEVICE_REMOVAL],
6662             &dr_feature_refcount);
6663         (void) feature_get_refcount(spa,
6664             &spa_feature_table[SPA_FEATURE_OBSOLETE_COUNTS],
6665             &oc_feature_refcount);
6666
6667         if (dr_feature_refcount != indirect_vdev_count) {
6668                 ret = 1;
6669                 (void) printf("Number of indirect vdevs (%llu) " \
6670                     "does not match feature count (%llu)\n",
6671                     (u_longlong_t)indirect_vdev_count,
6672                     (u_longlong_t)dr_feature_refcount);
6673         } else {
6674                 (void) printf("Verified device_removal feature refcount " \
6675                     "of %llu is correct\n",
6676                     (u_longlong_t)dr_feature_refcount);
6677         }
6678
6679         if (zap_contains(spa_meta_objset(spa), DMU_POOL_DIRECTORY_OBJECT,
6680             DMU_POOL_OBSOLETE_BPOBJ) == 0) {
6681                 obsolete_bpobj_count++;
6682         }
6683
6684
6685         obsolete_counts_object_count = precise_vdev_count;
6686         obsolete_counts_object_count += obsolete_sm_count;
6687         obsolete_counts_object_count += obsolete_counts_count;
6688         obsolete_counts_object_count += scip_count;
6689         obsolete_counts_object_count += obsolete_bpobj_count;
6690         obsolete_counts_object_count += remap_deadlist_count;
6691
6692         if (oc_feature_refcount != obsolete_counts_object_count) {
6693                 ret = 1;
6694                 (void) printf("Number of obsolete counts objects (%llu) " \
6695                     "does not match feature count (%llu)\n",
6696                     (u_longlong_t)obsolete_counts_object_count,
6697                     (u_longlong_t)oc_feature_refcount);
6698                 (void) printf("pv:%llu os:%llu oc:%llu sc:%llu "
6699                     "ob:%llu rd:%llu\n",
6700                     (u_longlong_t)precise_vdev_count,
6701                     (u_longlong_t)obsolete_sm_count,
6702                     (u_longlong_t)obsolete_counts_count,
6703                     (u_longlong_t)scip_count,
6704                     (u_longlong_t)obsolete_bpobj_count,
6705                     (u_longlong_t)remap_deadlist_count);
6706         } else {
6707                 (void) printf("Verified indirect_refcount feature refcount " \
6708                     "of %llu is correct\n",
6709                     (u_longlong_t)oc_feature_refcount);
6710         }
6711         return (ret);
6712 }
6713
6714 static void
6715 zdb_set_skip_mmp(char *target)
6716 {
6717         spa_t *spa;
6718
6719         /*
6720          * Disable the activity check to allow examination of
6721          * active pools.
6722          */
6723         mutex_enter(&spa_namespace_lock);
6724         if ((spa = spa_lookup(target)) != NULL) {
6725                 spa->spa_import_flags |= ZFS_IMPORT_SKIP_MMP;
6726         }
6727         mutex_exit(&spa_namespace_lock);
6728 }
6729
6730 #define BOGUS_SUFFIX "_CHECKPOINTED_UNIVERSE"
6731 /*
6732  * Import the checkpointed state of the pool specified by the target
6733  * parameter as readonly. The function also accepts a pool config
6734  * as an optional parameter, else it attempts to infer the config by
6735  * the name of the target pool.
6736  *
6737  * Note that the checkpointed state's pool name will be the name of
6738  * the original pool with the above suffix appended to it. In addition,
6739  * if the target is not a pool name (e.g. a path to a dataset) then
6740  * the new_path parameter is populated with the updated path to
6741  * reflect the fact that we are looking into the checkpointed state.
6742  *
6743  * The function returns a newly-allocated copy of the name of the
6744  * pool containing the checkpointed state. When this copy is no
6745  * longer needed it should be freed with free(3C). Same thing
6746  * applies to the new_path parameter if allocated.
6747  */
6748 static char *
6749 import_checkpointed_state(char *target, nvlist_t *cfg, char **new_path)
6750 {
6751         int error = 0;
6752         char *poolname, *bogus_name = NULL;
6753
6754         /* If the target is not a pool, the extract the pool name */
6755         char *path_start = strchr(target, '/');
6756         if (path_start != NULL) {
6757                 size_t poolname_len = path_start - target;
6758                 poolname = strndup(target, poolname_len);
6759         } else {
6760                 poolname = target;
6761         }
6762
6763         if (cfg == NULL) {
6764                 zdb_set_skip_mmp(poolname);
6765                 error = spa_get_stats(poolname, &cfg, NULL, 0);
6766                 if (error != 0) {
6767                         fatal("Tried to read config of pool \"%s\" but "
6768                             "spa_get_stats() failed with error %d\n",
6769                             poolname, error);
6770                 }
6771         }
6772
6773         if (asprintf(&bogus_name, "%s%s", poolname, BOGUS_SUFFIX) == -1)
6774                 return (NULL);
6775         fnvlist_add_string(cfg, ZPOOL_CONFIG_POOL_NAME, bogus_name);
6776
6777         error = spa_import(bogus_name, cfg, NULL,
6778             ZFS_IMPORT_MISSING_LOG | ZFS_IMPORT_CHECKPOINT |
6779             ZFS_IMPORT_SKIP_MMP);
6780         if (error != 0) {
6781                 fatal("Tried to import pool \"%s\" but spa_import() failed "
6782                     "with error %d\n", bogus_name, error);
6783         }
6784
6785         if (new_path != NULL && path_start != NULL) {
6786                 if (asprintf(new_path, "%s%s", bogus_name, path_start) == -1) {
6787                         if (path_start != NULL)
6788                                 free(poolname);
6789                         return (NULL);
6790                 }
6791         }
6792
6793         if (target != poolname)
6794                 free(poolname);
6795
6796         return (bogus_name);
6797 }
6798
6799 typedef struct verify_checkpoint_sm_entry_cb_arg {
6800         vdev_t *vcsec_vd;
6801
6802         /* the following fields are only used for printing progress */
6803         uint64_t vcsec_entryid;
6804         uint64_t vcsec_num_entries;
6805 } verify_checkpoint_sm_entry_cb_arg_t;
6806
6807 #define ENTRIES_PER_PROGRESS_UPDATE 10000
6808
6809 static int
6810 verify_checkpoint_sm_entry_cb(space_map_entry_t *sme, void *arg)
6811 {
6812         verify_checkpoint_sm_entry_cb_arg_t *vcsec = arg;
6813         vdev_t *vd = vcsec->vcsec_vd;
6814         metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
6815         uint64_t end = sme->sme_offset + sme->sme_run;
6816
6817         ASSERT(sme->sme_type == SM_FREE);
6818
6819         if ((vcsec->vcsec_entryid % ENTRIES_PER_PROGRESS_UPDATE) == 0) {
6820                 (void) fprintf(stderr,
6821                     "\rverifying vdev %llu, space map entry %llu of %llu ...",
6822                     (longlong_t)vd->vdev_id,
6823                     (longlong_t)vcsec->vcsec_entryid,
6824                     (longlong_t)vcsec->vcsec_num_entries);
6825         }
6826         vcsec->vcsec_entryid++;
6827
6828         /*
6829          * See comment in checkpoint_sm_exclude_entry_cb()
6830          */
6831         VERIFY3U(sme->sme_offset, >=, ms->ms_start);
6832         VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
6833
6834         /*
6835          * The entries in the vdev_checkpoint_sm should be marked as
6836          * allocated in the checkpointed state of the pool, therefore
6837          * their respective ms_allocateable trees should not contain them.
6838          */
6839         mutex_enter(&ms->ms_lock);
6840         range_tree_verify_not_present(ms->ms_allocatable,
6841             sme->sme_offset, sme->sme_run);
6842         mutex_exit(&ms->ms_lock);
6843
6844         return (0);
6845 }
6846
6847 /*
6848  * Verify that all segments in the vdev_checkpoint_sm are allocated
6849  * according to the checkpoint's ms_sm (i.e. are not in the checkpoint's
6850  * ms_allocatable).
6851  *
6852  * Do so by comparing the checkpoint space maps (vdev_checkpoint_sm) of
6853  * each vdev in the current state of the pool to the metaslab space maps
6854  * (ms_sm) of the checkpointed state of the pool.
6855  *
6856  * Note that the function changes the state of the ms_allocatable
6857  * trees of the current spa_t. The entries of these ms_allocatable
6858  * trees are cleared out and then repopulated from with the free
6859  * entries of their respective ms_sm space maps.
6860  */
6861 static void
6862 verify_checkpoint_vdev_spacemaps(spa_t *checkpoint, spa_t *current)
6863 {
6864         vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
6865         vdev_t *current_rvd = current->spa_root_vdev;
6866
6867         load_concrete_ms_allocatable_trees(checkpoint, SM_FREE);
6868
6869         for (uint64_t c = 0; c < ckpoint_rvd->vdev_children; c++) {
6870                 vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[c];
6871                 vdev_t *current_vd = current_rvd->vdev_child[c];
6872
6873                 space_map_t *checkpoint_sm = NULL;
6874                 uint64_t checkpoint_sm_obj;
6875
6876                 if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
6877                         /*
6878                          * Since we don't allow device removal in a pool
6879                          * that has a checkpoint, we expect that all removed
6880                          * vdevs were removed from the pool before the
6881                          * checkpoint.
6882                          */
6883                         ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
6884                         continue;
6885                 }
6886
6887                 /*
6888                  * If the checkpoint space map doesn't exist, then nothing
6889                  * here is checkpointed so there's nothing to verify.
6890                  */
6891                 if (current_vd->vdev_top_zap == 0 ||
6892                     zap_contains(spa_meta_objset(current),
6893                     current_vd->vdev_top_zap,
6894                     VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
6895                         continue;
6896
6897                 VERIFY0(zap_lookup(spa_meta_objset(current),
6898                     current_vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
6899                     sizeof (uint64_t), 1, &checkpoint_sm_obj));
6900
6901                 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(current),
6902                     checkpoint_sm_obj, 0, current_vd->vdev_asize,
6903                     current_vd->vdev_ashift));
6904
6905                 verify_checkpoint_sm_entry_cb_arg_t vcsec;
6906                 vcsec.vcsec_vd = ckpoint_vd;
6907                 vcsec.vcsec_entryid = 0;
6908                 vcsec.vcsec_num_entries =
6909                     space_map_length(checkpoint_sm) / sizeof (uint64_t);
6910                 VERIFY0(space_map_iterate(checkpoint_sm,
6911                     space_map_length(checkpoint_sm),
6912                     verify_checkpoint_sm_entry_cb, &vcsec));
6913                 if (dump_opt['m'] > 3)
6914                         dump_spacemap(current->spa_meta_objset, checkpoint_sm);
6915                 space_map_close(checkpoint_sm);
6916         }
6917
6918         /*
6919          * If we've added vdevs since we took the checkpoint, ensure
6920          * that their checkpoint space maps are empty.
6921          */
6922         if (ckpoint_rvd->vdev_children < current_rvd->vdev_children) {
6923                 for (uint64_t c = ckpoint_rvd->vdev_children;
6924                     c < current_rvd->vdev_children; c++) {
6925                         vdev_t *current_vd = current_rvd->vdev_child[c];
6926                         ASSERT3P(current_vd->vdev_checkpoint_sm, ==, NULL);
6927                 }
6928         }
6929
6930         /* for cleaner progress output */
6931         (void) fprintf(stderr, "\n");
6932 }
6933
6934 /*
6935  * Verifies that all space that's allocated in the checkpoint is
6936  * still allocated in the current version, by checking that everything
6937  * in checkpoint's ms_allocatable (which is actually allocated, not
6938  * allocatable/free) is not present in current's ms_allocatable.
6939  *
6940  * Note that the function changes the state of the ms_allocatable
6941  * trees of both spas when called. The entries of all ms_allocatable
6942  * trees are cleared out and then repopulated from their respective
6943  * ms_sm space maps. In the checkpointed state we load the allocated
6944  * entries, and in the current state we load the free entries.
6945  */
6946 static void
6947 verify_checkpoint_ms_spacemaps(spa_t *checkpoint, spa_t *current)
6948 {
6949         vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
6950         vdev_t *current_rvd = current->spa_root_vdev;
6951
6952         load_concrete_ms_allocatable_trees(checkpoint, SM_ALLOC);
6953         load_concrete_ms_allocatable_trees(current, SM_FREE);
6954
6955         for (uint64_t i = 0; i < ckpoint_rvd->vdev_children; i++) {
6956                 vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[i];
6957                 vdev_t *current_vd = current_rvd->vdev_child[i];
6958
6959                 if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
6960                         /*
6961                          * See comment in verify_checkpoint_vdev_spacemaps()
6962                          */
6963                         ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
6964                         continue;
6965                 }
6966
6967                 for (uint64_t m = 0; m < ckpoint_vd->vdev_ms_count; m++) {
6968                         metaslab_t *ckpoint_msp = ckpoint_vd->vdev_ms[m];
6969                         metaslab_t *current_msp = current_vd->vdev_ms[m];
6970
6971                         (void) fprintf(stderr,
6972                             "\rverifying vdev %llu of %llu, "
6973                             "metaslab %llu of %llu ...",
6974                             (longlong_t)current_vd->vdev_id,
6975                             (longlong_t)current_rvd->vdev_children,
6976                             (longlong_t)current_vd->vdev_ms[m]->ms_id,
6977                             (longlong_t)current_vd->vdev_ms_count);
6978
6979                         /*
6980                          * We walk through the ms_allocatable trees that
6981                          * are loaded with the allocated blocks from the
6982                          * ms_sm spacemaps of the checkpoint. For each
6983                          * one of these ranges we ensure that none of them
6984                          * exists in the ms_allocatable trees of the
6985                          * current state which are loaded with the ranges
6986                          * that are currently free.
6987                          *
6988                          * This way we ensure that none of the blocks that
6989                          * are part of the checkpoint were freed by mistake.
6990                          */
6991                         range_tree_walk(ckpoint_msp->ms_allocatable,
6992                             (range_tree_func_t *)range_tree_verify_not_present,
6993                             current_msp->ms_allocatable);
6994                 }
6995         }
6996
6997         /* for cleaner progress output */
6998         (void) fprintf(stderr, "\n");
6999 }
7000
7001 static void
7002 verify_checkpoint_blocks(spa_t *spa)
7003 {
7004         ASSERT(!dump_opt['L']);
7005
7006         spa_t *checkpoint_spa;
7007         char *checkpoint_pool;
7008         nvlist_t *config = NULL;
7009         int error = 0;
7010
7011         /*
7012          * We import the checkpointed state of the pool (under a different
7013          * name) so we can do verification on it against the current state
7014          * of the pool.
7015          */
7016         checkpoint_pool = import_checkpointed_state(spa->spa_name, config,
7017             NULL);
7018         ASSERT(strcmp(spa->spa_name, checkpoint_pool) != 0);
7019
7020         error = spa_open(checkpoint_pool, &checkpoint_spa, FTAG);
7021         if (error != 0) {
7022                 fatal("Tried to open pool \"%s\" but spa_open() failed with "
7023                     "error %d\n", checkpoint_pool, error);
7024         }
7025
7026         /*
7027          * Ensure that ranges in the checkpoint space maps of each vdev
7028          * are allocated according to the checkpointed state's metaslab
7029          * space maps.
7030          */
7031         verify_checkpoint_vdev_spacemaps(checkpoint_spa, spa);
7032
7033         /*
7034          * Ensure that allocated ranges in the checkpoint's metaslab
7035          * space maps remain allocated in the metaslab space maps of
7036          * the current state.
7037          */
7038         verify_checkpoint_ms_spacemaps(checkpoint_spa, spa);
7039
7040         /*
7041          * Once we are done, we get rid of the checkpointed state.
7042          */
7043         spa_close(checkpoint_spa, FTAG);
7044         free(checkpoint_pool);
7045 }
7046
7047 static void
7048 dump_leftover_checkpoint_blocks(spa_t *spa)
7049 {
7050         vdev_t *rvd = spa->spa_root_vdev;
7051
7052         for (uint64_t i = 0; i < rvd->vdev_children; i++) {
7053                 vdev_t *vd = rvd->vdev_child[i];
7054
7055                 space_map_t *checkpoint_sm = NULL;
7056                 uint64_t checkpoint_sm_obj;
7057
7058                 if (vd->vdev_top_zap == 0)
7059                         continue;
7060
7061                 if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
7062                     VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
7063                         continue;
7064
7065                 VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
7066                     VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
7067                     sizeof (uint64_t), 1, &checkpoint_sm_obj));
7068
7069                 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
7070                     checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
7071                 dump_spacemap(spa->spa_meta_objset, checkpoint_sm);
7072                 space_map_close(checkpoint_sm);
7073         }
7074 }
7075
7076 static int
7077 verify_checkpoint(spa_t *spa)
7078 {
7079         uberblock_t checkpoint;
7080         int error;
7081
7082         if (!spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT))
7083                 return (0);
7084
7085         error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7086             DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
7087             sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
7088
7089         if (error == ENOENT && !dump_opt['L']) {
7090                 /*
7091                  * If the feature is active but the uberblock is missing
7092                  * then we must be in the middle of discarding the
7093                  * checkpoint.
7094                  */
7095                 (void) printf("\nPartially discarded checkpoint "
7096                     "state found:\n");
7097                 if (dump_opt['m'] > 3)
7098                         dump_leftover_checkpoint_blocks(spa);
7099                 return (0);
7100         } else if (error != 0) {
7101                 (void) printf("lookup error %d when looking for "
7102                     "checkpointed uberblock in MOS\n", error);
7103                 return (error);
7104         }
7105         dump_uberblock(&checkpoint, "\nCheckpointed uberblock found:\n", "\n");
7106
7107         if (checkpoint.ub_checkpoint_txg == 0) {
7108                 (void) printf("\nub_checkpoint_txg not set in checkpointed "
7109                     "uberblock\n");
7110                 error = 3;
7111         }
7112
7113         if (error == 0 && !dump_opt['L'])
7114                 verify_checkpoint_blocks(spa);
7115
7116         return (error);
7117 }
7118
7119 /* ARGSUSED */
7120 static void
7121 mos_leaks_cb(void *arg, uint64_t start, uint64_t size)
7122 {
7123         for (uint64_t i = start; i < size; i++) {
7124                 (void) printf("MOS object %llu referenced but not allocated\n",
7125                     (u_longlong_t)i);
7126         }
7127 }
7128
7129 static void
7130 mos_obj_refd(uint64_t obj)
7131 {
7132         if (obj != 0 && mos_refd_objs != NULL)
7133                 range_tree_add(mos_refd_objs, obj, 1);
7134 }
7135
7136 /*
7137  * Call on a MOS object that may already have been referenced.
7138  */
7139 static void
7140 mos_obj_refd_multiple(uint64_t obj)
7141 {
7142         if (obj != 0 && mos_refd_objs != NULL &&
7143             !range_tree_contains(mos_refd_objs, obj, 1))
7144                 range_tree_add(mos_refd_objs, obj, 1);
7145 }
7146
7147 static void
7148 mos_leak_vdev_top_zap(vdev_t *vd)
7149 {
7150         uint64_t ms_flush_data_obj;
7151         int error = zap_lookup(spa_meta_objset(vd->vdev_spa),
7152             vd->vdev_top_zap, VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS,
7153             sizeof (ms_flush_data_obj), 1, &ms_flush_data_obj);
7154         if (error == ENOENT)
7155                 return;
7156         ASSERT0(error);
7157
7158         mos_obj_refd(ms_flush_data_obj);
7159 }
7160
7161 static void
7162 mos_leak_vdev(vdev_t *vd)
7163 {
7164         mos_obj_refd(vd->vdev_dtl_object);
7165         mos_obj_refd(vd->vdev_ms_array);
7166         mos_obj_refd(vd->vdev_indirect_config.vic_births_object);
7167         mos_obj_refd(vd->vdev_indirect_config.vic_mapping_object);
7168         mos_obj_refd(vd->vdev_leaf_zap);
7169         if (vd->vdev_checkpoint_sm != NULL)
7170                 mos_obj_refd(vd->vdev_checkpoint_sm->sm_object);
7171         if (vd->vdev_indirect_mapping != NULL) {
7172                 mos_obj_refd(vd->vdev_indirect_mapping->
7173                     vim_phys->vimp_counts_object);
7174         }
7175         if (vd->vdev_obsolete_sm != NULL)
7176                 mos_obj_refd(vd->vdev_obsolete_sm->sm_object);
7177
7178         for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
7179                 metaslab_t *ms = vd->vdev_ms[m];
7180                 mos_obj_refd(space_map_object(ms->ms_sm));
7181         }
7182
7183         if (vd->vdev_top_zap != 0) {
7184                 mos_obj_refd(vd->vdev_top_zap);
7185                 mos_leak_vdev_top_zap(vd);
7186         }
7187
7188         for (uint64_t c = 0; c < vd->vdev_children; c++) {
7189                 mos_leak_vdev(vd->vdev_child[c]);
7190         }
7191 }
7192
7193 static void
7194 mos_leak_log_spacemaps(spa_t *spa)
7195 {
7196         uint64_t spacemap_zap;
7197         int error = zap_lookup(spa_meta_objset(spa),
7198             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_LOG_SPACEMAP_ZAP,
7199             sizeof (spacemap_zap), 1, &spacemap_zap);
7200         if (error == ENOENT)
7201                 return;
7202         ASSERT0(error);
7203
7204         mos_obj_refd(spacemap_zap);
7205         for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
7206             sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls))
7207                 mos_obj_refd(sls->sls_sm_obj);
7208 }
7209
7210 static int
7211 dump_mos_leaks(spa_t *spa)
7212 {
7213         int rv = 0;
7214         objset_t *mos = spa->spa_meta_objset;
7215         dsl_pool_t *dp = spa->spa_dsl_pool;
7216
7217         /* Visit and mark all referenced objects in the MOS */
7218
7219         mos_obj_refd(DMU_POOL_DIRECTORY_OBJECT);
7220         mos_obj_refd(spa->spa_pool_props_object);
7221         mos_obj_refd(spa->spa_config_object);
7222         mos_obj_refd(spa->spa_ddt_stat_object);
7223         mos_obj_refd(spa->spa_feat_desc_obj);
7224         mos_obj_refd(spa->spa_feat_enabled_txg_obj);
7225         mos_obj_refd(spa->spa_feat_for_read_obj);
7226         mos_obj_refd(spa->spa_feat_for_write_obj);
7227         mos_obj_refd(spa->spa_history);
7228         mos_obj_refd(spa->spa_errlog_last);
7229         mos_obj_refd(spa->spa_errlog_scrub);
7230         mos_obj_refd(spa->spa_all_vdev_zaps);
7231         mos_obj_refd(spa->spa_dsl_pool->dp_bptree_obj);
7232         mos_obj_refd(spa->spa_dsl_pool->dp_tmp_userrefs_obj);
7233         mos_obj_refd(spa->spa_dsl_pool->dp_scan->scn_phys.scn_queue_obj);
7234         bpobj_count_refd(&spa->spa_deferred_bpobj);
7235         mos_obj_refd(dp->dp_empty_bpobj);
7236         bpobj_count_refd(&dp->dp_obsolete_bpobj);
7237         bpobj_count_refd(&dp->dp_free_bpobj);
7238         mos_obj_refd(spa->spa_l2cache.sav_object);
7239         mos_obj_refd(spa->spa_spares.sav_object);
7240
7241         if (spa->spa_syncing_log_sm != NULL)
7242                 mos_obj_refd(spa->spa_syncing_log_sm->sm_object);
7243         mos_leak_log_spacemaps(spa);
7244
7245         mos_obj_refd(spa->spa_condensing_indirect_phys.
7246             scip_next_mapping_object);
7247         mos_obj_refd(spa->spa_condensing_indirect_phys.
7248             scip_prev_obsolete_sm_object);
7249         if (spa->spa_condensing_indirect_phys.scip_next_mapping_object != 0) {
7250                 vdev_indirect_mapping_t *vim =
7251                     vdev_indirect_mapping_open(mos,
7252                     spa->spa_condensing_indirect_phys.scip_next_mapping_object);
7253                 mos_obj_refd(vim->vim_phys->vimp_counts_object);
7254                 vdev_indirect_mapping_close(vim);
7255         }
7256         deleted_livelists_dump_mos(spa);
7257
7258         if (dp->dp_origin_snap != NULL) {
7259                 dsl_dataset_t *ds;
7260
7261                 dsl_pool_config_enter(dp, FTAG);
7262                 VERIFY0(dsl_dataset_hold_obj(dp,
7263                     dsl_dataset_phys(dp->dp_origin_snap)->ds_next_snap_obj,
7264                     FTAG, &ds));
7265                 count_ds_mos_objects(ds);
7266                 dump_blkptr_list(&ds->ds_deadlist, "Deadlist");
7267                 dsl_dataset_rele(ds, FTAG);
7268                 dsl_pool_config_exit(dp, FTAG);
7269
7270                 count_ds_mos_objects(dp->dp_origin_snap);
7271                 dump_blkptr_list(&dp->dp_origin_snap->ds_deadlist, "Deadlist");
7272         }
7273         count_dir_mos_objects(dp->dp_mos_dir);
7274         if (dp->dp_free_dir != NULL)
7275                 count_dir_mos_objects(dp->dp_free_dir);
7276         if (dp->dp_leak_dir != NULL)
7277                 count_dir_mos_objects(dp->dp_leak_dir);
7278
7279         mos_leak_vdev(spa->spa_root_vdev);
7280
7281         for (uint64_t class = 0; class < DDT_CLASSES; class++) {
7282                 for (uint64_t type = 0; type < DDT_TYPES; type++) {
7283                         for (uint64_t cksum = 0;
7284                             cksum < ZIO_CHECKSUM_FUNCTIONS; cksum++) {
7285                                 ddt_t *ddt = spa->spa_ddt[cksum];
7286                                 mos_obj_refd(ddt->ddt_object[type][class]);
7287                         }
7288                 }
7289         }
7290
7291         /*
7292          * Visit all allocated objects and make sure they are referenced.
7293          */
7294         uint64_t object = 0;
7295         while (dmu_object_next(mos, &object, B_FALSE, 0) == 0) {
7296                 if (range_tree_contains(mos_refd_objs, object, 1)) {
7297                         range_tree_remove(mos_refd_objs, object, 1);
7298                 } else {
7299                         dmu_object_info_t doi;
7300                         const char *name;
7301                         dmu_object_info(mos, object, &doi);
7302                         if (doi.doi_type & DMU_OT_NEWTYPE) {
7303                                 dmu_object_byteswap_t bswap =
7304                                     DMU_OT_BYTESWAP(doi.doi_type);
7305                                 name = dmu_ot_byteswap[bswap].ob_name;
7306                         } else {
7307                                 name = dmu_ot[doi.doi_type].ot_name;
7308                         }
7309
7310                         (void) printf("MOS object %llu (%s) leaked\n",
7311                             (u_longlong_t)object, name);
7312                         rv = 2;
7313                 }
7314         }
7315         (void) range_tree_walk(mos_refd_objs, mos_leaks_cb, NULL);
7316         if (!range_tree_is_empty(mos_refd_objs))
7317                 rv = 2;
7318         range_tree_vacate(mos_refd_objs, NULL, NULL);
7319         range_tree_destroy(mos_refd_objs);
7320         return (rv);
7321 }
7322
7323 typedef struct log_sm_obsolete_stats_arg {
7324         uint64_t lsos_current_txg;
7325
7326         uint64_t lsos_total_entries;
7327         uint64_t lsos_valid_entries;
7328
7329         uint64_t lsos_sm_entries;
7330         uint64_t lsos_valid_sm_entries;
7331 } log_sm_obsolete_stats_arg_t;
7332
7333 static int
7334 log_spacemap_obsolete_stats_cb(spa_t *spa, space_map_entry_t *sme,
7335     uint64_t txg, void *arg)
7336 {
7337         log_sm_obsolete_stats_arg_t *lsos = arg;
7338
7339         uint64_t offset = sme->sme_offset;
7340         uint64_t vdev_id = sme->sme_vdev;
7341
7342         if (lsos->lsos_current_txg == 0) {
7343                 /* this is the first log */
7344                 lsos->lsos_current_txg = txg;
7345         } else if (lsos->lsos_current_txg < txg) {
7346                 /* we just changed log - print stats and reset */
7347                 (void) printf("%-8llu valid entries out of %-8llu - txg %llu\n",
7348                     (u_longlong_t)lsos->lsos_valid_sm_entries,
7349                     (u_longlong_t)lsos->lsos_sm_entries,
7350                     (u_longlong_t)lsos->lsos_current_txg);
7351                 lsos->lsos_valid_sm_entries = 0;
7352                 lsos->lsos_sm_entries = 0;
7353                 lsos->lsos_current_txg = txg;
7354         }
7355         ASSERT3U(lsos->lsos_current_txg, ==, txg);
7356
7357         lsos->lsos_sm_entries++;
7358         lsos->lsos_total_entries++;
7359
7360         vdev_t *vd = vdev_lookup_top(spa, vdev_id);
7361         if (!vdev_is_concrete(vd))
7362                 return (0);
7363
7364         metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
7365         ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
7366
7367         if (txg < metaslab_unflushed_txg(ms))
7368                 return (0);
7369         lsos->lsos_valid_sm_entries++;
7370         lsos->lsos_valid_entries++;
7371         return (0);
7372 }
7373
7374 static void
7375 dump_log_spacemap_obsolete_stats(spa_t *spa)
7376 {
7377         if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
7378                 return;
7379
7380         log_sm_obsolete_stats_arg_t lsos;
7381         bzero(&lsos, sizeof (lsos));
7382
7383         (void) printf("Log Space Map Obsolete Entry Statistics:\n");
7384
7385         iterate_through_spacemap_logs(spa,
7386             log_spacemap_obsolete_stats_cb, &lsos);
7387
7388         /* print stats for latest log */
7389         (void) printf("%-8llu valid entries out of %-8llu - txg %llu\n",
7390             (u_longlong_t)lsos.lsos_valid_sm_entries,
7391             (u_longlong_t)lsos.lsos_sm_entries,
7392             (u_longlong_t)lsos.lsos_current_txg);
7393
7394         (void) printf("%-8llu valid entries out of %-8llu - total\n\n",
7395             (u_longlong_t)lsos.lsos_valid_entries,
7396             (u_longlong_t)lsos.lsos_total_entries);
7397 }
7398
7399 static void
7400 dump_zpool(spa_t *spa)
7401 {
7402         dsl_pool_t *dp = spa_get_dsl(spa);
7403         int rc = 0;
7404
7405         if (dump_opt['y']) {
7406                 livelist_metaslab_validate(spa);
7407         }
7408
7409         if (dump_opt['S']) {
7410                 dump_simulated_ddt(spa);
7411                 return;
7412         }
7413
7414         if (!dump_opt['e'] && dump_opt['C'] > 1) {
7415                 (void) printf("\nCached configuration:\n");
7416                 dump_nvlist(spa->spa_config, 8);
7417         }
7418
7419         if (dump_opt['C'])
7420                 dump_config(spa);
7421
7422         if (dump_opt['u'])
7423                 dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
7424
7425         if (dump_opt['D'])
7426                 dump_all_ddts(spa);
7427
7428         if (dump_opt['d'] > 2 || dump_opt['m'])
7429                 dump_metaslabs(spa);
7430         if (dump_opt['M'])
7431                 dump_metaslab_groups(spa);
7432         if (dump_opt['d'] > 2 || dump_opt['m']) {
7433                 dump_log_spacemaps(spa);
7434                 dump_log_spacemap_obsolete_stats(spa);
7435         }
7436
7437         if (dump_opt['d'] || dump_opt['i']) {
7438                 spa_feature_t f;
7439                 mos_refd_objs = range_tree_create(NULL, RANGE_SEG64, NULL, 0,
7440                     0);
7441                 dump_objset(dp->dp_meta_objset);
7442
7443                 if (dump_opt['d'] >= 3) {
7444                         dsl_pool_t *dp = spa->spa_dsl_pool;
7445                         dump_full_bpobj(&spa->spa_deferred_bpobj,
7446                             "Deferred frees", 0);
7447                         if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
7448                                 dump_full_bpobj(&dp->dp_free_bpobj,
7449                                     "Pool snapshot frees", 0);
7450                         }
7451                         if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
7452                                 ASSERT(spa_feature_is_enabled(spa,
7453                                     SPA_FEATURE_DEVICE_REMOVAL));
7454                                 dump_full_bpobj(&dp->dp_obsolete_bpobj,
7455                                     "Pool obsolete blocks", 0);
7456                         }
7457
7458                         if (spa_feature_is_active(spa,
7459                             SPA_FEATURE_ASYNC_DESTROY)) {
7460                                 dump_bptree(spa->spa_meta_objset,
7461                                     dp->dp_bptree_obj,
7462                                     "Pool dataset frees");
7463                         }
7464                         dump_dtl(spa->spa_root_vdev, 0);
7465                 }
7466
7467                 for (spa_feature_t f = 0; f < SPA_FEATURES; f++)
7468                         global_feature_count[f] = UINT64_MAX;
7469                 global_feature_count[SPA_FEATURE_REDACTION_BOOKMARKS] = 0;
7470                 global_feature_count[SPA_FEATURE_BOOKMARK_WRITTEN] = 0;
7471                 global_feature_count[SPA_FEATURE_LIVELIST] = 0;
7472
7473                 (void) dmu_objset_find(spa_name(spa), dump_one_objset,
7474                     NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
7475
7476                 if (rc == 0 && !dump_opt['L'])
7477                         rc = dump_mos_leaks(spa);
7478
7479                 for (f = 0; f < SPA_FEATURES; f++) {
7480                         uint64_t refcount;
7481
7482                         uint64_t *arr;
7483                         if (!(spa_feature_table[f].fi_flags &
7484                             ZFEATURE_FLAG_PER_DATASET)) {
7485                                 if (global_feature_count[f] == UINT64_MAX)
7486                                         continue;
7487                                 if (!spa_feature_is_enabled(spa, f)) {
7488                                         ASSERT0(global_feature_count[f]);
7489                                         continue;
7490                                 }
7491                                 arr = global_feature_count;
7492                         } else {
7493                                 if (!spa_feature_is_enabled(spa, f)) {
7494                                         ASSERT0(dataset_feature_count[f]);
7495                                         continue;
7496                                 }
7497                                 arr = dataset_feature_count;
7498                         }
7499                         if (feature_get_refcount(spa, &spa_feature_table[f],
7500                             &refcount) == ENOTSUP)
7501                                 continue;
7502                         if (arr[f] != refcount) {
7503                                 (void) printf("%s feature refcount mismatch: "
7504                                     "%lld consumers != %lld refcount\n",
7505                                     spa_feature_table[f].fi_uname,
7506                                     (longlong_t)arr[f], (longlong_t)refcount);
7507                                 rc = 2;
7508                         } else {
7509                                 (void) printf("Verified %s feature refcount "
7510                                     "of %llu is correct\n",
7511                                     spa_feature_table[f].fi_uname,
7512                                     (longlong_t)refcount);
7513                         }
7514                 }
7515
7516                 if (rc == 0)
7517                         rc = verify_device_removal_feature_counts(spa);
7518         }
7519
7520         if (rc == 0 && (dump_opt['b'] || dump_opt['c']))
7521                 rc = dump_block_stats(spa);
7522
7523         if (rc == 0)
7524                 rc = verify_spacemap_refcounts(spa);
7525
7526         if (dump_opt['s'])
7527                 show_pool_stats(spa);
7528
7529         if (dump_opt['h'])
7530                 dump_history(spa);
7531
7532         if (rc == 0)
7533                 rc = verify_checkpoint(spa);
7534
7535         if (rc != 0) {
7536                 dump_debug_buffer();
7537                 exit(rc);
7538         }
7539 }
7540
7541 #define ZDB_FLAG_CHECKSUM       0x0001
7542 #define ZDB_FLAG_DECOMPRESS     0x0002
7543 #define ZDB_FLAG_BSWAP          0x0004
7544 #define ZDB_FLAG_GBH            0x0008
7545 #define ZDB_FLAG_INDIRECT       0x0010
7546 #define ZDB_FLAG_RAW            0x0020
7547 #define ZDB_FLAG_PRINT_BLKPTR   0x0040
7548 #define ZDB_FLAG_VERBOSE        0x0080
7549
7550 static int flagbits[256];
7551 static char flagbitstr[16];
7552
7553 static void
7554 zdb_print_blkptr(const blkptr_t *bp, int flags)
7555 {
7556         char blkbuf[BP_SPRINTF_LEN];
7557
7558         if (flags & ZDB_FLAG_BSWAP)
7559                 byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
7560
7561         snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
7562         (void) printf("%s\n", blkbuf);
7563 }
7564
7565 static void
7566 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
7567 {
7568         int i;
7569
7570         for (i = 0; i < nbps; i++)
7571                 zdb_print_blkptr(&bp[i], flags);
7572 }
7573
7574 static void
7575 zdb_dump_gbh(void *buf, int flags)
7576 {
7577         zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
7578 }
7579
7580 static void
7581 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
7582 {
7583         if (flags & ZDB_FLAG_BSWAP)
7584                 byteswap_uint64_array(buf, size);
7585         VERIFY(write(fileno(stdout), buf, size) == size);
7586 }
7587
7588 static void
7589 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
7590 {
7591         uint64_t *d = (uint64_t *)buf;
7592         unsigned nwords = size / sizeof (uint64_t);
7593         int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
7594         unsigned i, j;
7595         const char *hdr;
7596         char *c;
7597
7598
7599         if (do_bswap)
7600                 hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
7601         else
7602                 hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
7603
7604         (void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
7605
7606 #ifdef _LITTLE_ENDIAN
7607         /* correct the endianness */
7608         do_bswap = !do_bswap;
7609 #endif
7610         for (i = 0; i < nwords; i += 2) {
7611                 (void) printf("%06llx:  %016llx  %016llx  ",
7612                     (u_longlong_t)(i * sizeof (uint64_t)),
7613                     (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
7614                     (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
7615
7616                 c = (char *)&d[i];
7617                 for (j = 0; j < 2 * sizeof (uint64_t); j++)
7618                         (void) printf("%c", isprint(c[j]) ? c[j] : '.');
7619                 (void) printf("\n");
7620         }
7621 }
7622
7623 /*
7624  * There are two acceptable formats:
7625  *      leaf_name         - For example: c1t0d0 or /tmp/ztest.0a
7626  *      child[.child]*    - For example: 0.1.1
7627  *
7628  * The second form can be used to specify arbitrary vdevs anywhere
7629  * in the hierarchy.  For example, in a pool with a mirror of
7630  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
7631  */
7632 static vdev_t *
7633 zdb_vdev_lookup(vdev_t *vdev, const char *path)
7634 {
7635         char *s, *p, *q;
7636         unsigned i;
7637
7638         if (vdev == NULL)
7639                 return (NULL);
7640
7641         /* First, assume the x.x.x.x format */
7642         i = strtoul(path, &s, 10);
7643         if (s == path || (s && *s != '.' && *s != '\0'))
7644                 goto name;
7645         if (i >= vdev->vdev_children)
7646                 return (NULL);
7647
7648         vdev = vdev->vdev_child[i];
7649         if (s && *s == '\0')
7650                 return (vdev);
7651         return (zdb_vdev_lookup(vdev, s+1));
7652
7653 name:
7654         for (i = 0; i < vdev->vdev_children; i++) {
7655                 vdev_t *vc = vdev->vdev_child[i];
7656
7657                 if (vc->vdev_path == NULL) {
7658                         vc = zdb_vdev_lookup(vc, path);
7659                         if (vc == NULL)
7660                                 continue;
7661                         else
7662                                 return (vc);
7663                 }
7664
7665                 p = strrchr(vc->vdev_path, '/');
7666                 p = p ? p + 1 : vc->vdev_path;
7667                 q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
7668
7669                 if (strcmp(vc->vdev_path, path) == 0)
7670                         return (vc);
7671                 if (strcmp(p, path) == 0)
7672                         return (vc);
7673                 if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
7674                         return (vc);
7675         }
7676
7677         return (NULL);
7678 }
7679
7680 static int
7681 name_from_objset_id(spa_t *spa, uint64_t objset_id, char *outstr)
7682 {
7683         dsl_dataset_t *ds;
7684
7685         dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
7686         int error = dsl_dataset_hold_obj(spa->spa_dsl_pool, objset_id,
7687             NULL, &ds);
7688         if (error != 0) {
7689                 (void) fprintf(stderr, "failed to hold objset %llu: %s\n",
7690                     (u_longlong_t)objset_id, strerror(error));
7691                 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
7692                 return (error);
7693         }
7694         dsl_dataset_name(ds, outstr);
7695         dsl_dataset_rele(ds, NULL);
7696         dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
7697         return (0);
7698 }
7699
7700 static boolean_t
7701 zdb_parse_block_sizes(char *sizes, uint64_t *lsize, uint64_t *psize)
7702 {
7703         char *s0, *s1;
7704
7705         if (sizes == NULL)
7706                 return (B_FALSE);
7707
7708         s0 = strtok(sizes, "/");
7709         if (s0 == NULL)
7710                 return (B_FALSE);
7711         s1 = strtok(NULL, "/");
7712         *lsize = strtoull(s0, NULL, 16);
7713         *psize = s1 ? strtoull(s1, NULL, 16) : *lsize;
7714         return (*lsize >= *psize && *psize > 0);
7715 }
7716
7717 #define ZIO_COMPRESS_MASK(alg)  (1ULL << (ZIO_COMPRESS_##alg))
7718
7719 static boolean_t
7720 zdb_decompress_block(abd_t *pabd, void *buf, void *lbuf, uint64_t lsize,
7721     uint64_t psize, int flags)
7722 {
7723         boolean_t exceeded = B_FALSE;
7724         /*
7725          * We don't know how the data was compressed, so just try
7726          * every decompress function at every inflated blocksize.
7727          */
7728         void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
7729         int cfuncs[ZIO_COMPRESS_FUNCTIONS] = { 0 };
7730         int *cfuncp = cfuncs;
7731         uint64_t maxlsize = SPA_MAXBLOCKSIZE;
7732         uint64_t mask = ZIO_COMPRESS_MASK(ON) | ZIO_COMPRESS_MASK(OFF) |
7733             ZIO_COMPRESS_MASK(INHERIT) | ZIO_COMPRESS_MASK(EMPTY) |
7734             (getenv("ZDB_NO_ZLE") ? ZIO_COMPRESS_MASK(ZLE) : 0);
7735         *cfuncp++ = ZIO_COMPRESS_LZ4;
7736         *cfuncp++ = ZIO_COMPRESS_LZJB;
7737         mask |= ZIO_COMPRESS_MASK(LZ4) | ZIO_COMPRESS_MASK(LZJB);
7738         for (int c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++)
7739                 if (((1ULL << c) & mask) == 0)
7740                         *cfuncp++ = c;
7741
7742         /*
7743          * On the one hand, with SPA_MAXBLOCKSIZE at 16MB, this
7744          * could take a while and we should let the user know
7745          * we are not stuck.  On the other hand, printing progress
7746          * info gets old after a while.  User can specify 'v' flag
7747          * to see the progression.
7748          */
7749         if (lsize == psize)
7750                 lsize += SPA_MINBLOCKSIZE;
7751         else
7752                 maxlsize = lsize;
7753         for (; lsize <= maxlsize; lsize += SPA_MINBLOCKSIZE) {
7754                 for (cfuncp = cfuncs; *cfuncp; cfuncp++) {
7755                         if (flags & ZDB_FLAG_VERBOSE) {
7756                                 (void) fprintf(stderr,
7757                                     "Trying %05llx -> %05llx (%s)\n",
7758                                     (u_longlong_t)psize,
7759                                     (u_longlong_t)lsize,
7760                                     zio_compress_table[*cfuncp].\
7761                                     ci_name);
7762                         }
7763
7764                         /*
7765                          * We randomize lbuf2, and decompress to both
7766                          * lbuf and lbuf2. This way, we will know if
7767                          * decompression fill exactly to lsize.
7768                          */
7769                         VERIFY0(random_get_pseudo_bytes(lbuf2, lsize));
7770
7771                         if (zio_decompress_data(*cfuncp, pabd,
7772                             lbuf, psize, lsize, NULL) == 0 &&
7773                             zio_decompress_data(*cfuncp, pabd,
7774                             lbuf2, psize, lsize, NULL) == 0 &&
7775                             bcmp(lbuf, lbuf2, lsize) == 0)
7776                                 break;
7777                 }
7778                 if (*cfuncp != 0)
7779                         break;
7780         }
7781         umem_free(lbuf2, SPA_MAXBLOCKSIZE);
7782
7783         if (lsize > maxlsize) {
7784                 exceeded = B_TRUE;
7785         }
7786         buf = lbuf;
7787         if (*cfuncp == ZIO_COMPRESS_ZLE) {
7788                 printf("\nZLE decompression was selected. If you "
7789                     "suspect the results are wrong,\ntry avoiding ZLE "
7790                     "by setting and exporting ZDB_NO_ZLE=\"true\"\n");
7791         }
7792
7793         return (exceeded);
7794 }
7795
7796 /*
7797  * Read a block from a pool and print it out.  The syntax of the
7798  * block descriptor is:
7799  *
7800  *      pool:vdev_specifier:offset:[lsize/]psize[:flags]
7801  *
7802  *      pool           - The name of the pool you wish to read from
7803  *      vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
7804  *      offset         - offset, in hex, in bytes
7805  *      size           - Amount of data to read, in hex, in bytes
7806  *      flags          - A string of characters specifying options
7807  *               b: Decode a blkptr at given offset within block
7808  *               c: Calculate and display checksums
7809  *               d: Decompress data before dumping
7810  *               e: Byteswap data before dumping
7811  *               g: Display data as a gang block header
7812  *               i: Display as an indirect block
7813  *               r: Dump raw data to stdout
7814  *               v: Verbose
7815  *
7816  */
7817 static void
7818 zdb_read_block(char *thing, spa_t *spa)
7819 {
7820         blkptr_t blk, *bp = &blk;
7821         dva_t *dva = bp->blk_dva;
7822         int flags = 0;
7823         uint64_t offset = 0, psize = 0, lsize = 0, blkptr_offset = 0;
7824         zio_t *zio;
7825         vdev_t *vd;
7826         abd_t *pabd;
7827         void *lbuf, *buf;
7828         char *s, *p, *dup, *vdev, *flagstr, *sizes;
7829         int i, error;
7830         boolean_t borrowed = B_FALSE, found = B_FALSE;
7831
7832         dup = strdup(thing);
7833         s = strtok(dup, ":");
7834         vdev = s ? s : "";
7835         s = strtok(NULL, ":");
7836         offset = strtoull(s ? s : "", NULL, 16);
7837         sizes = strtok(NULL, ":");
7838         s = strtok(NULL, ":");
7839         flagstr = strdup(s ? s : "");
7840
7841         s = NULL;
7842         if (!zdb_parse_block_sizes(sizes, &lsize, &psize))
7843                 s = "invalid size(s)";
7844         if (!IS_P2ALIGNED(psize, DEV_BSIZE) || !IS_P2ALIGNED(lsize, DEV_BSIZE))
7845                 s = "size must be a multiple of sector size";
7846         if (!IS_P2ALIGNED(offset, DEV_BSIZE))
7847                 s = "offset must be a multiple of sector size";
7848         if (s) {
7849                 (void) printf("Invalid block specifier: %s  - %s\n", thing, s);
7850                 goto done;
7851         }
7852
7853         for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
7854                 for (i = 0; i < strlen(flagstr); i++) {
7855                         int bit = flagbits[(uchar_t)flagstr[i]];
7856
7857                         if (bit == 0) {
7858                                 (void) printf("***Ignoring flag: %c\n",
7859                                     (uchar_t)flagstr[i]);
7860                                 continue;
7861                         }
7862                         found = B_TRUE;
7863                         flags |= bit;
7864
7865                         p = &flagstr[i + 1];
7866                         if (*p != ':' && *p != '\0') {
7867                                 int j = 0, nextbit = flagbits[(uchar_t)*p];
7868                                 char *end, offstr[8] = { 0 };
7869                                 if ((bit == ZDB_FLAG_PRINT_BLKPTR) &&
7870                                     (nextbit == 0)) {
7871                                         /* look ahead to isolate the offset */
7872                                         while (nextbit == 0 &&
7873                                             strchr(flagbitstr, *p) == NULL) {
7874                                                 offstr[j] = *p;
7875                                                 j++;
7876                                                 if (i + j > strlen(flagstr))
7877                                                         break;
7878                                                 p++;
7879                                                 nextbit = flagbits[(uchar_t)*p];
7880                                         }
7881                                         blkptr_offset = strtoull(offstr, &end,
7882                                             16);
7883                                         i += j;
7884                                 } else if (nextbit == 0) {
7885                                         (void) printf("***Ignoring flag arg:"
7886                                             " '%c'\n", (uchar_t)*p);
7887                                 }
7888                         }
7889                 }
7890         }
7891         if (blkptr_offset % sizeof (blkptr_t)) {
7892                 printf("Block pointer offset 0x%llx "
7893                     "must be divisible by 0x%x\n",
7894                     (longlong_t)blkptr_offset, (int)sizeof (blkptr_t));
7895                 goto done;
7896         }
7897         if (found == B_FALSE && strlen(flagstr) > 0) {
7898                 printf("Invalid flag arg: '%s'\n", flagstr);
7899                 goto done;
7900         }
7901
7902         vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
7903         if (vd == NULL) {
7904                 (void) printf("***Invalid vdev: %s\n", vdev);
7905                 free(dup);
7906                 return;
7907         } else {
7908                 if (vd->vdev_path)
7909                         (void) fprintf(stderr, "Found vdev: %s\n",
7910                             vd->vdev_path);
7911                 else
7912                         (void) fprintf(stderr, "Found vdev type: %s\n",
7913                             vd->vdev_ops->vdev_op_type);
7914         }
7915
7916         pabd = abd_alloc_for_io(SPA_MAXBLOCKSIZE, B_FALSE);
7917         lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
7918
7919         BP_ZERO(bp);
7920
7921         DVA_SET_VDEV(&dva[0], vd->vdev_id);
7922         DVA_SET_OFFSET(&dva[0], offset);
7923         DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
7924         DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
7925
7926         BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
7927
7928         BP_SET_LSIZE(bp, lsize);
7929         BP_SET_PSIZE(bp, psize);
7930         BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
7931         BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
7932         BP_SET_TYPE(bp, DMU_OT_NONE);
7933         BP_SET_LEVEL(bp, 0);
7934         BP_SET_DEDUP(bp, 0);
7935         BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
7936
7937         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7938         zio = zio_root(spa, NULL, NULL, 0);
7939
7940         if (vd == vd->vdev_top) {
7941                 /*
7942                  * Treat this as a normal block read.
7943                  */
7944                 zio_nowait(zio_read(zio, spa, bp, pabd, psize, NULL, NULL,
7945                     ZIO_PRIORITY_SYNC_READ,
7946                     ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
7947         } else {
7948                 /*
7949                  * Treat this as a vdev child I/O.
7950                  */
7951                 zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pabd,
7952                     psize, ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
7953                     ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_PROPAGATE |
7954                     ZIO_FLAG_DONT_RETRY | ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW |
7955                     ZIO_FLAG_OPTIONAL, NULL, NULL));
7956         }
7957
7958         error = zio_wait(zio);
7959         spa_config_exit(spa, SCL_STATE, FTAG);
7960
7961         if (error) {
7962                 (void) printf("Read of %s failed, error: %d\n", thing, error);
7963                 goto out;
7964         }
7965
7966         uint64_t orig_lsize = lsize;
7967         buf = lbuf;
7968         if (flags & ZDB_FLAG_DECOMPRESS) {
7969                 boolean_t failed = zdb_decompress_block(pabd, buf, lbuf,
7970                     lsize, psize, flags);
7971                 if (failed) {
7972                         (void) printf("Decompress of %s failed\n", thing);
7973                         goto out;
7974                 }
7975         } else {
7976                 buf = abd_borrow_buf_copy(pabd, lsize);
7977                 borrowed = B_TRUE;
7978         }
7979         /*
7980          * Try to detect invalid block pointer.  If invalid, try
7981          * decompressing.
7982          */
7983         if ((flags & ZDB_FLAG_PRINT_BLKPTR || flags & ZDB_FLAG_INDIRECT) &&
7984             !(flags & ZDB_FLAG_DECOMPRESS)) {
7985                 const blkptr_t *b = (const blkptr_t *)(void *)
7986                     ((uintptr_t)buf + (uintptr_t)blkptr_offset);
7987                 if (zfs_blkptr_verify(spa, b, B_FALSE, BLK_VERIFY_ONLY) ==
7988                     B_FALSE) {
7989                         abd_return_buf_copy(pabd, buf, lsize);
7990                         borrowed = B_FALSE;
7991                         buf = lbuf;
7992                         boolean_t failed = zdb_decompress_block(pabd, buf,
7993                             lbuf, lsize, psize, flags);
7994                         b = (const blkptr_t *)(void *)
7995                             ((uintptr_t)buf + (uintptr_t)blkptr_offset);
7996                         if (failed || zfs_blkptr_verify(spa, b, B_FALSE,
7997                             BLK_VERIFY_LOG) == B_FALSE) {
7998                                 printf("invalid block pointer at this DVA\n");
7999                                 goto out;
8000                         }
8001                 }
8002         }
8003
8004         if (flags & ZDB_FLAG_PRINT_BLKPTR)
8005                 zdb_print_blkptr((blkptr_t *)(void *)
8006                     ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
8007         else if (flags & ZDB_FLAG_RAW)
8008                 zdb_dump_block_raw(buf, lsize, flags);
8009         else if (flags & ZDB_FLAG_INDIRECT)
8010                 zdb_dump_indirect((blkptr_t *)buf,
8011                     orig_lsize / sizeof (blkptr_t), flags);
8012         else if (flags & ZDB_FLAG_GBH)
8013                 zdb_dump_gbh(buf, flags);
8014         else
8015                 zdb_dump_block(thing, buf, lsize, flags);
8016
8017         /*
8018          * If :c was specified, iterate through the checksum table to
8019          * calculate and display each checksum for our specified
8020          * DVA and length.
8021          */
8022         if ((flags & ZDB_FLAG_CHECKSUM) && !(flags & ZDB_FLAG_RAW) &&
8023             !(flags & ZDB_FLAG_GBH)) {
8024                 zio_t *czio;
8025                 (void) printf("\n");
8026                 for (enum zio_checksum ck = ZIO_CHECKSUM_LABEL;
8027                     ck < ZIO_CHECKSUM_FUNCTIONS; ck++) {
8028
8029                         if ((zio_checksum_table[ck].ci_flags &
8030                             ZCHECKSUM_FLAG_EMBEDDED) ||
8031                             ck == ZIO_CHECKSUM_NOPARITY) {
8032                                 continue;
8033                         }
8034                         BP_SET_CHECKSUM(bp, ck);
8035                         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8036                         czio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
8037                         czio->io_bp = bp;
8038
8039                         if (vd == vd->vdev_top) {
8040                                 zio_nowait(zio_read(czio, spa, bp, pabd, psize,
8041                                     NULL, NULL,
8042                                     ZIO_PRIORITY_SYNC_READ,
8043                                     ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW |
8044                                     ZIO_FLAG_DONT_RETRY, NULL));
8045                         } else {
8046                                 zio_nowait(zio_vdev_child_io(czio, bp, vd,
8047                                     offset, pabd, psize, ZIO_TYPE_READ,
8048                                     ZIO_PRIORITY_SYNC_READ,
8049                                     ZIO_FLAG_DONT_CACHE |
8050                                     ZIO_FLAG_DONT_PROPAGATE |
8051                                     ZIO_FLAG_DONT_RETRY |
8052                                     ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW |
8053                                     ZIO_FLAG_SPECULATIVE |
8054                                     ZIO_FLAG_OPTIONAL, NULL, NULL));
8055                         }
8056                         error = zio_wait(czio);
8057                         if (error == 0 || error == ECKSUM) {
8058                                 zio_t *ck_zio = zio_root(spa, NULL, NULL, 0);
8059                                 ck_zio->io_offset =
8060                                     DVA_GET_OFFSET(&bp->blk_dva[0]);
8061                                 ck_zio->io_bp = bp;
8062                                 zio_checksum_compute(ck_zio, ck, pabd, lsize);
8063                                 printf("%12s\tcksum=%llx:%llx:%llx:%llx\n",
8064                                     zio_checksum_table[ck].ci_name,
8065                                     (u_longlong_t)bp->blk_cksum.zc_word[0],
8066                                     (u_longlong_t)bp->blk_cksum.zc_word[1],
8067                                     (u_longlong_t)bp->blk_cksum.zc_word[2],
8068                                     (u_longlong_t)bp->blk_cksum.zc_word[3]);
8069                                 zio_wait(ck_zio);
8070                         } else {
8071                                 printf("error %d reading block\n", error);
8072                         }
8073                         spa_config_exit(spa, SCL_STATE, FTAG);
8074                 }
8075         }
8076
8077         if (borrowed)
8078                 abd_return_buf_copy(pabd, buf, lsize);
8079
8080 out:
8081         abd_free(pabd);
8082         umem_free(lbuf, SPA_MAXBLOCKSIZE);
8083 done:
8084         free(flagstr);
8085         free(dup);
8086 }
8087
8088 static void
8089 zdb_embedded_block(char *thing)
8090 {
8091         blkptr_t bp;
8092         unsigned long long *words = (void *)&bp;
8093         char *buf;
8094         int err;
8095
8096         bzero(&bp, sizeof (bp));
8097         err = sscanf(thing, "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx:"
8098             "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx",
8099             words + 0, words + 1, words + 2, words + 3,
8100             words + 4, words + 5, words + 6, words + 7,
8101             words + 8, words + 9, words + 10, words + 11,
8102             words + 12, words + 13, words + 14, words + 15);
8103         if (err != 16) {
8104                 (void) fprintf(stderr, "invalid input format\n");
8105                 exit(1);
8106         }
8107         ASSERT3U(BPE_GET_LSIZE(&bp), <=, SPA_MAXBLOCKSIZE);
8108         buf = malloc(SPA_MAXBLOCKSIZE);
8109         if (buf == NULL) {
8110                 (void) fprintf(stderr, "out of memory\n");
8111                 exit(1);
8112         }
8113         err = decode_embedded_bp(&bp, buf, BPE_GET_LSIZE(&bp));
8114         if (err != 0) {
8115                 (void) fprintf(stderr, "decode failed: %u\n", err);
8116                 exit(1);
8117         }
8118         zdb_dump_block_raw(buf, BPE_GET_LSIZE(&bp), 0);
8119         free(buf);
8120 }
8121
8122 int
8123 main(int argc, char **argv)
8124 {
8125         int c;
8126         struct rlimit rl = { 1024, 1024 };
8127         spa_t *spa = NULL;
8128         objset_t *os = NULL;
8129         int dump_all = 1;
8130         int verbose = 0;
8131         int error = 0;
8132         char **searchdirs = NULL;
8133         int nsearch = 0;
8134         char *target, *target_pool, dsname[ZFS_MAX_DATASET_NAME_LEN];
8135         nvlist_t *policy = NULL;
8136         uint64_t max_txg = UINT64_MAX;
8137         int64_t objset_id = -1;
8138         int flags = ZFS_IMPORT_MISSING_LOG;
8139         int rewind = ZPOOL_NEVER_REWIND;
8140         char *spa_config_path_env, *objset_str;
8141         boolean_t target_is_spa = B_TRUE, dataset_lookup = B_FALSE;
8142         nvlist_t *cfg = NULL;
8143
8144         (void) setrlimit(RLIMIT_NOFILE, &rl);
8145         (void) enable_extended_FILE_stdio(-1, -1);
8146
8147         dprintf_setup(&argc, argv);
8148
8149         /*
8150          * If there is an environment variable SPA_CONFIG_PATH it overrides
8151          * default spa_config_path setting. If -U flag is specified it will
8152          * override this environment variable settings once again.
8153          */
8154         spa_config_path_env = getenv("SPA_CONFIG_PATH");
8155         if (spa_config_path_env != NULL)
8156                 spa_config_path = spa_config_path_env;
8157
8158         /*
8159          * For performance reasons, we set this tunable down. We do so before
8160          * the arg parsing section so that the user can override this value if
8161          * they choose.
8162          */
8163         zfs_btree_verify_intensity = 3;
8164
8165         while ((c = getopt(argc, argv,
8166             "AbcCdDeEFGhiI:klLmMo:Op:PqRsSt:uU:vVx:XYyZ")) != -1) {
8167                 switch (c) {
8168                 case 'b':
8169                 case 'c':
8170                 case 'C':
8171                 case 'd':
8172                 case 'D':
8173                 case 'E':
8174                 case 'G':
8175                 case 'h':
8176                 case 'i':
8177                 case 'l':
8178                 case 'm':
8179                 case 'M':
8180                 case 'O':
8181                 case 'R':
8182                 case 's':
8183                 case 'S':
8184                 case 'u':
8185                 case 'y':
8186                 case 'Z':
8187                         dump_opt[c]++;
8188                         dump_all = 0;
8189                         break;
8190                 case 'A':
8191                 case 'e':
8192                 case 'F':
8193                 case 'k':
8194                 case 'L':
8195                 case 'P':
8196                 case 'q':
8197                 case 'X':
8198                         dump_opt[c]++;
8199                         break;
8200                 case 'Y':
8201                         zfs_reconstruct_indirect_combinations_max = INT_MAX;
8202                         zfs_deadman_enabled = 0;
8203                         break;
8204                 /* NB: Sort single match options below. */
8205                 case 'I':
8206                         max_inflight_bytes = strtoull(optarg, NULL, 0);
8207                         if (max_inflight_bytes == 0) {
8208                                 (void) fprintf(stderr, "maximum number "
8209                                     "of inflight bytes must be greater "
8210                                     "than 0\n");
8211                                 usage();
8212                         }
8213                         break;
8214                 case 'o':
8215                         error = set_global_var(optarg);
8216                         if (error != 0)
8217                                 usage();
8218                         break;
8219                 case 'p':
8220                         if (searchdirs == NULL) {
8221                                 searchdirs = umem_alloc(sizeof (char *),
8222                                     UMEM_NOFAIL);
8223                         } else {
8224                                 char **tmp = umem_alloc((nsearch + 1) *
8225                                     sizeof (char *), UMEM_NOFAIL);
8226                                 bcopy(searchdirs, tmp, nsearch *
8227                                     sizeof (char *));
8228                                 umem_free(searchdirs,
8229                                     nsearch * sizeof (char *));
8230                                 searchdirs = tmp;
8231                         }
8232                         searchdirs[nsearch++] = optarg;
8233                         break;
8234                 case 't':
8235                         max_txg = strtoull(optarg, NULL, 0);
8236                         if (max_txg < TXG_INITIAL) {
8237                                 (void) fprintf(stderr, "incorrect txg "
8238                                     "specified: %s\n", optarg);
8239                                 usage();
8240                         }
8241                         break;
8242                 case 'U':
8243                         spa_config_path = optarg;
8244                         if (spa_config_path[0] != '/') {
8245                                 (void) fprintf(stderr,
8246                                     "cachefile must be an absolute path "
8247                                     "(i.e. start with a slash)\n");
8248                                 usage();
8249                         }
8250                         break;
8251                 case 'v':
8252                         verbose++;
8253                         break;
8254                 case 'V':
8255                         flags = ZFS_IMPORT_VERBATIM;
8256                         break;
8257                 case 'x':
8258                         vn_dumpdir = optarg;
8259                         break;
8260                 default:
8261                         usage();
8262                         break;
8263                 }
8264         }
8265
8266         if (!dump_opt['e'] && searchdirs != NULL) {
8267                 (void) fprintf(stderr, "-p option requires use of -e\n");
8268                 usage();
8269         }
8270         if (dump_opt['d']) {
8271                 /* <pool>[/<dataset | objset id> is accepted */
8272                 if (argv[2] && (objset_str = strchr(argv[2], '/')) != NULL &&
8273                     objset_str++ != NULL) {
8274                         char *endptr;
8275                         errno = 0;
8276                         objset_id = strtoull(objset_str, &endptr, 0);
8277                         /* dataset 0 is the same as opening the pool */
8278                         if (errno == 0 && endptr != objset_str &&
8279                             objset_id != 0) {
8280                                 target_is_spa = B_FALSE;
8281                                 dataset_lookup = B_TRUE;
8282                         } else if (objset_id != 0) {
8283                                 printf("failed to open objset %s "
8284                                     "%llu %s", objset_str,
8285                                     (u_longlong_t)objset_id,
8286                                     strerror(errno));
8287                                 exit(1);
8288                         }
8289                         /* normal dataset name not an objset ID */
8290                         if (endptr == objset_str) {
8291                                 objset_id = -1;
8292                         }
8293                 }
8294         }
8295
8296 #if defined(_LP64)
8297         /*
8298          * ZDB does not typically re-read blocks; therefore limit the ARC
8299          * to 256 MB, which can be used entirely for metadata.
8300          */
8301         zfs_arc_min = zfs_arc_meta_min = 2ULL << SPA_MAXBLOCKSHIFT;
8302         zfs_arc_max = zfs_arc_meta_limit = 256 * 1024 * 1024;
8303 #endif
8304
8305         /*
8306          * "zdb -c" uses checksum-verifying scrub i/os which are async reads.
8307          * "zdb -b" uses traversal prefetch which uses async reads.
8308          * For good performance, let several of them be active at once.
8309          */
8310         zfs_vdev_async_read_max_active = 10;
8311
8312         /*
8313          * Disable reference tracking for better performance.
8314          */
8315         reference_tracking_enable = B_FALSE;
8316
8317         /*
8318          * Do not fail spa_load when spa_load_verify fails. This is needed
8319          * to load non-idle pools.
8320          */
8321         spa_load_verify_dryrun = B_TRUE;
8322
8323         kernel_init(SPA_MODE_READ);
8324
8325         if (dump_all)
8326                 verbose = MAX(verbose, 1);
8327
8328         for (c = 0; c < 256; c++) {
8329                 if (dump_all && strchr("AeEFklLOPRSXy", c) == NULL)
8330                         dump_opt[c] = 1;
8331                 if (dump_opt[c])
8332                         dump_opt[c] += verbose;
8333         }
8334
8335         aok = (dump_opt['A'] == 1) || (dump_opt['A'] > 2);
8336         zfs_recover = (dump_opt['A'] > 1);
8337
8338         argc -= optind;
8339         argv += optind;
8340         if (argc < 2 && dump_opt['R'])
8341                 usage();
8342
8343         if (dump_opt['E']) {
8344                 if (argc != 1)
8345                         usage();
8346                 zdb_embedded_block(argv[0]);
8347                 return (0);
8348         }
8349
8350         if (argc < 1) {
8351                 if (!dump_opt['e'] && dump_opt['C']) {
8352                         dump_cachefile(spa_config_path);
8353                         return (0);
8354                 }
8355                 usage();
8356         }
8357
8358         if (dump_opt['l'])
8359                 return (dump_label(argv[0]));
8360
8361         if (dump_opt['O']) {
8362                 if (argc != 2)
8363                         usage();
8364                 dump_opt['v'] = verbose + 3;
8365                 return (dump_path(argv[0], argv[1]));
8366         }
8367
8368         if (dump_opt['X'] || dump_opt['F'])
8369                 rewind = ZPOOL_DO_REWIND |
8370                     (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
8371
8372         if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
8373             nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, max_txg) != 0 ||
8374             nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY, rewind) != 0)
8375                 fatal("internal error: %s", strerror(ENOMEM));
8376
8377         error = 0;
8378         target = argv[0];
8379
8380         if (strpbrk(target, "/@") != NULL) {
8381                 size_t targetlen;
8382
8383                 target_pool = strdup(target);
8384                 *strpbrk(target_pool, "/@") = '\0';
8385
8386                 target_is_spa = B_FALSE;
8387                 targetlen = strlen(target);
8388                 if (targetlen && target[targetlen - 1] == '/')
8389                         target[targetlen - 1] = '\0';
8390         } else {
8391                 target_pool = target;
8392         }
8393
8394         if (dump_opt['e']) {
8395                 importargs_t args = { 0 };
8396
8397                 args.paths = nsearch;
8398                 args.path = searchdirs;
8399                 args.can_be_active = B_TRUE;
8400
8401                 error = zpool_find_config(NULL, target_pool, &cfg, &args,
8402                     &libzpool_config_ops);
8403
8404                 if (error == 0) {
8405
8406                         if (nvlist_add_nvlist(cfg,
8407                             ZPOOL_LOAD_POLICY, policy) != 0) {
8408                                 fatal("can't open '%s': %s",
8409                                     target, strerror(ENOMEM));
8410                         }
8411
8412                         if (dump_opt['C'] > 1) {
8413                                 (void) printf("\nConfiguration for import:\n");
8414                                 dump_nvlist(cfg, 8);
8415                         }
8416
8417                         /*
8418                          * Disable the activity check to allow examination of
8419                          * active pools.
8420                          */
8421                         error = spa_import(target_pool, cfg, NULL,
8422                             flags | ZFS_IMPORT_SKIP_MMP);
8423                 }
8424         }
8425
8426         /*
8427          * import_checkpointed_state makes the assumption that the
8428          * target pool that we pass it is already part of the spa
8429          * namespace. Because of that we need to make sure to call
8430          * it always after the -e option has been processed, which
8431          * imports the pool to the namespace if it's not in the
8432          * cachefile.
8433          */
8434         char *checkpoint_pool = NULL;
8435         char *checkpoint_target = NULL;
8436         if (dump_opt['k']) {
8437                 checkpoint_pool = import_checkpointed_state(target, cfg,
8438                     &checkpoint_target);
8439
8440                 if (checkpoint_target != NULL)
8441                         target = checkpoint_target;
8442         }
8443
8444         if (target_pool != target)
8445                 free(target_pool);
8446
8447         if (error == 0) {
8448                 if (dump_opt['k'] && (target_is_spa || dump_opt['R'])) {
8449                         ASSERT(checkpoint_pool != NULL);
8450                         ASSERT(checkpoint_target == NULL);
8451
8452                         error = spa_open(checkpoint_pool, &spa, FTAG);
8453                         if (error != 0) {
8454                                 fatal("Tried to open pool \"%s\" but "
8455                                     "spa_open() failed with error %d\n",
8456                                     checkpoint_pool, error);
8457                         }
8458
8459                 } else if (target_is_spa || dump_opt['R'] || objset_id == 0) {
8460                         zdb_set_skip_mmp(target);
8461                         error = spa_open_rewind(target, &spa, FTAG, policy,
8462                             NULL);
8463                         if (error) {
8464                                 /*
8465                                  * If we're missing the log device then
8466                                  * try opening the pool after clearing the
8467                                  * log state.
8468                                  */
8469                                 mutex_enter(&spa_namespace_lock);
8470                                 if ((spa = spa_lookup(target)) != NULL &&
8471                                     spa->spa_log_state == SPA_LOG_MISSING) {
8472                                         spa->spa_log_state = SPA_LOG_CLEAR;
8473                                         error = 0;
8474                                 }
8475                                 mutex_exit(&spa_namespace_lock);
8476
8477                                 if (!error) {
8478                                         error = spa_open_rewind(target, &spa,
8479                                             FTAG, policy, NULL);
8480                                 }
8481                         }
8482                 } else if (strpbrk(target, "#") != NULL) {
8483                         dsl_pool_t *dp;
8484                         error = dsl_pool_hold(target, FTAG, &dp);
8485                         if (error != 0) {
8486                                 fatal("can't dump '%s': %s", target,
8487                                     strerror(error));
8488                         }
8489                         error = dump_bookmark(dp, target, B_TRUE, verbose > 1);
8490                         dsl_pool_rele(dp, FTAG);
8491                         if (error != 0) {
8492                                 fatal("can't dump '%s': %s", target,
8493                                     strerror(error));
8494                         }
8495                         return (error);
8496                 } else {
8497                         zdb_set_skip_mmp(target);
8498                         if (dataset_lookup == B_TRUE) {
8499                                 /*
8500                                  * Use the supplied id to get the name
8501                                  * for open_objset.
8502                                  */
8503                                 error = spa_open(target, &spa, FTAG);
8504                                 if (error == 0) {
8505                                         error = name_from_objset_id(spa,
8506                                             objset_id, dsname);
8507                                         spa_close(spa, FTAG);
8508                                         if (error == 0)
8509                                                 target = dsname;
8510                                 }
8511                         }
8512                         if (error == 0)
8513                                 error = open_objset(target, FTAG, &os);
8514                         if (error == 0)
8515                                 spa = dmu_objset_spa(os);
8516                 }
8517         }
8518         nvlist_free(policy);
8519
8520         if (error)
8521                 fatal("can't open '%s': %s", target, strerror(error));
8522
8523         /*
8524          * Set the pool failure mode to panic in order to prevent the pool
8525          * from suspending.  A suspended I/O will have no way to resume and
8526          * can prevent the zdb(8) command from terminating as expected.
8527          */
8528         if (spa != NULL)
8529                 spa->spa_failmode = ZIO_FAILURE_MODE_PANIC;
8530
8531         argv++;
8532         argc--;
8533         if (!dump_opt['R']) {
8534                 flagbits['d'] = ZOR_FLAG_DIRECTORY;
8535                 flagbits['f'] = ZOR_FLAG_PLAIN_FILE;
8536                 flagbits['m'] = ZOR_FLAG_SPACE_MAP;
8537                 flagbits['z'] = ZOR_FLAG_ZAP;
8538                 flagbits['A'] = ZOR_FLAG_ALL_TYPES;
8539
8540                 if (argc > 0 && dump_opt['d']) {
8541                         zopt_object_args = argc;
8542                         zopt_object_ranges = calloc(zopt_object_args,
8543                             sizeof (zopt_object_range_t));
8544                         for (unsigned i = 0; i < zopt_object_args; i++) {
8545                                 int err;
8546                                 char *msg = NULL;
8547
8548                                 err = parse_object_range(argv[i],
8549                                     &zopt_object_ranges[i], &msg);
8550                                 if (err != 0)
8551                                         fatal("Bad object or range: '%s': %s\n",
8552                                             argv[i], msg ? msg : "");
8553                         }
8554                 } else if (argc > 0 && dump_opt['m']) {
8555                         zopt_metaslab_args = argc;
8556                         zopt_metaslab = calloc(zopt_metaslab_args,
8557                             sizeof (uint64_t));
8558                         for (unsigned i = 0; i < zopt_metaslab_args; i++) {
8559                                 errno = 0;
8560                                 zopt_metaslab[i] = strtoull(argv[i], NULL, 0);
8561                                 if (zopt_metaslab[i] == 0 && errno != 0)
8562                                         fatal("bad number %s: %s", argv[i],
8563                                             strerror(errno));
8564                         }
8565                 }
8566                 if (os != NULL) {
8567                         dump_objset(os);
8568                 } else if (zopt_object_args > 0 && !dump_opt['m']) {
8569                         dump_objset(spa->spa_meta_objset);
8570                 } else {
8571                         dump_zpool(spa);
8572                 }
8573         } else {
8574                 flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
8575                 flagbits['c'] = ZDB_FLAG_CHECKSUM;
8576                 flagbits['d'] = ZDB_FLAG_DECOMPRESS;
8577                 flagbits['e'] = ZDB_FLAG_BSWAP;
8578                 flagbits['g'] = ZDB_FLAG_GBH;
8579                 flagbits['i'] = ZDB_FLAG_INDIRECT;
8580                 flagbits['r'] = ZDB_FLAG_RAW;
8581                 flagbits['v'] = ZDB_FLAG_VERBOSE;
8582
8583                 for (int i = 0; i < argc; i++)
8584                         zdb_read_block(argv[i], spa);
8585         }
8586
8587         if (dump_opt['k']) {
8588                 free(checkpoint_pool);
8589                 if (!target_is_spa)
8590                         free(checkpoint_target);
8591         }
8592
8593         if (os != NULL) {
8594                 close_objset(os, FTAG);
8595         } else {
8596                 spa_close(spa, FTAG);
8597         }
8598
8599         fuid_table_destroy();
8600
8601         dump_debug_buffer();
8602
8603         kernel_fini();
8604
8605         return (error);
8606 }