zdb: add extra -T flag to show histograms of BRT refcounts
[zfs.git] / cmd / zdb / zdb.c
blob46587671202a46725f6f5a94db9d6094480940c0
1 /*
2 * CDDL HEADER START
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.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or https://opensource.org/licenses/CDDL-1.0.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
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]
19 * CDDL HEADER END
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]
32 * [1] Portions of this software were developed by Allan Jude
33 * under sponsorship from the FreeBSD Foundation.
34 * Copyright (c) 2021 Allan Jude
35 * Copyright (c) 2021 Toomas Soome <tsoome@me.com>
36 * Copyright (c) 2023, 2024, Klara Inc.
37 * Copyright (c) 2023, Rob Norris <robn@despairlabs.com>
40 #include <stdio.h>
41 #include <unistd.h>
42 #include <stdlib.h>
43 #include <ctype.h>
44 #include <getopt.h>
45 #include <openssl/evp.h>
46 #include <sys/zfs_context.h>
47 #include <sys/spa.h>
48 #include <sys/spa_impl.h>
49 #include <sys/dmu.h>
50 #include <sys/zap.h>
51 #include <sys/zap_impl.h>
52 #include <sys/fs/zfs.h>
53 #include <sys/zfs_znode.h>
54 #include <sys/zfs_sa.h>
55 #include <sys/sa.h>
56 #include <sys/sa_impl.h>
57 #include <sys/vdev.h>
58 #include <sys/vdev_impl.h>
59 #include <sys/metaslab_impl.h>
60 #include <sys/dmu_objset.h>
61 #include <sys/dsl_dir.h>
62 #include <sys/dsl_dataset.h>
63 #include <sys/dsl_pool.h>
64 #include <sys/dsl_bookmark.h>
65 #include <sys/dbuf.h>
66 #include <sys/zil.h>
67 #include <sys/zil_impl.h>
68 #include <sys/stat.h>
69 #include <sys/resource.h>
70 #include <sys/dmu_send.h>
71 #include <sys/dmu_traverse.h>
72 #include <sys/zio_checksum.h>
73 #include <sys/zio_compress.h>
74 #include <sys/zfs_fuid.h>
75 #include <sys/arc.h>
76 #include <sys/arc_impl.h>
77 #include <sys/ddt.h>
78 #include <sys/ddt_impl.h>
79 #include <sys/zfeature.h>
80 #include <sys/abd.h>
81 #include <sys/blkptr.h>
82 #include <sys/dsl_crypt.h>
83 #include <sys/dsl_scan.h>
84 #include <sys/btree.h>
85 #include <sys/brt.h>
86 #include <sys/brt_impl.h>
87 #include <zfs_comutil.h>
88 #include <sys/zstd/zstd.h>
89 #include <sys/backtrace.h>
91 #include <libnvpair.h>
92 #include <libzutil.h>
93 #include <libzfs_core.h>
95 #include <libzdb.h>
97 #include "zdb.h"
100 extern int reference_tracking_enable;
101 extern int zfs_recover;
102 extern uint_t zfs_vdev_async_read_max_active;
103 extern boolean_t spa_load_verify_dryrun;
104 extern boolean_t spa_mode_readable_spacemaps;
105 extern uint_t zfs_reconstruct_indirect_combinations_max;
106 extern uint_t zfs_btree_verify_intensity;
108 static const char cmdname[] = "zdb";
109 uint8_t dump_opt[256];
111 typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
113 static uint64_t *zopt_metaslab = NULL;
114 static unsigned zopt_metaslab_args = 0;
117 static zopt_object_range_t *zopt_object_ranges = NULL;
118 static unsigned zopt_object_args = 0;
120 static int flagbits[256];
123 static uint64_t max_inflight_bytes = 256 * 1024 * 1024; /* 256MB */
124 static int leaked_objects = 0;
125 static range_tree_t *mos_refd_objs;
126 static spa_t *spa;
127 static objset_t *os;
128 static boolean_t kernel_init_done;
130 static void snprintf_blkptr_compact(char *, size_t, const blkptr_t *,
131 boolean_t);
132 static void mos_obj_refd(uint64_t);
133 static void mos_obj_refd_multiple(uint64_t);
134 static int dump_bpobj_cb(void *arg, const blkptr_t *bp, boolean_t free,
135 dmu_tx_t *tx);
139 static void zdb_print_blkptr(const blkptr_t *bp, int flags);
140 static void zdb_exit(int reason);
142 typedef struct sublivelist_verify_block_refcnt {
143 /* block pointer entry in livelist being verified */
144 blkptr_t svbr_blk;
147 * Refcount gets incremented to 1 when we encounter the first
148 * FREE entry for the svfbr block pointer and a node for it
149 * is created in our ZDB verification/tracking metadata.
151 * As we encounter more FREE entries we increment this counter
152 * and similarly decrement it whenever we find the respective
153 * ALLOC entries for this block.
155 * When the refcount gets to 0 it means that all the FREE and
156 * ALLOC entries of this block have paired up and we no longer
157 * need to track it in our verification logic (e.g. the node
158 * containing this struct in our verification data structure
159 * should be freed).
161 * [refer to sublivelist_verify_blkptr() for the actual code]
163 uint32_t svbr_refcnt;
164 } sublivelist_verify_block_refcnt_t;
166 static int
167 sublivelist_block_refcnt_compare(const void *larg, const void *rarg)
169 const sublivelist_verify_block_refcnt_t *l = larg;
170 const sublivelist_verify_block_refcnt_t *r = rarg;
171 return (livelist_compare(&l->svbr_blk, &r->svbr_blk));
174 static int
175 sublivelist_verify_blkptr(void *arg, const blkptr_t *bp, boolean_t free,
176 dmu_tx_t *tx)
178 ASSERT3P(tx, ==, NULL);
179 struct sublivelist_verify *sv = arg;
180 sublivelist_verify_block_refcnt_t current = {
181 .svbr_blk = *bp,
184 * Start with 1 in case this is the first free entry.
185 * This field is not used for our B-Tree comparisons
186 * anyway.
188 .svbr_refcnt = 1,
191 zfs_btree_index_t where;
192 sublivelist_verify_block_refcnt_t *pair =
193 zfs_btree_find(&sv->sv_pair, &current, &where);
194 if (free) {
195 if (pair == NULL) {
196 /* first free entry for this block pointer */
197 zfs_btree_add(&sv->sv_pair, &current);
198 } else {
199 pair->svbr_refcnt++;
201 } else {
202 if (pair == NULL) {
203 /* block that is currently marked as allocated */
204 for (int i = 0; i < SPA_DVAS_PER_BP; i++) {
205 if (DVA_IS_EMPTY(&bp->blk_dva[i]))
206 break;
207 sublivelist_verify_block_t svb = {
208 .svb_dva = bp->blk_dva[i],
209 .svb_allocated_txg =
210 BP_GET_LOGICAL_BIRTH(bp)
213 if (zfs_btree_find(&sv->sv_leftover, &svb,
214 &where) == NULL) {
215 zfs_btree_add_idx(&sv->sv_leftover,
216 &svb, &where);
219 } else {
220 /* alloc matches a free entry */
221 pair->svbr_refcnt--;
222 if (pair->svbr_refcnt == 0) {
223 /* all allocs and frees have been matched */
224 zfs_btree_remove_idx(&sv->sv_pair, &where);
229 return (0);
232 static int
233 sublivelist_verify_func(void *args, dsl_deadlist_entry_t *dle)
235 int err;
236 struct sublivelist_verify *sv = args;
238 zfs_btree_create(&sv->sv_pair, sublivelist_block_refcnt_compare, NULL,
239 sizeof (sublivelist_verify_block_refcnt_t));
241 err = bpobj_iterate_nofree(&dle->dle_bpobj, sublivelist_verify_blkptr,
242 sv, NULL);
244 sublivelist_verify_block_refcnt_t *e;
245 zfs_btree_index_t *cookie = NULL;
246 while ((e = zfs_btree_destroy_nodes(&sv->sv_pair, &cookie)) != NULL) {
247 char blkbuf[BP_SPRINTF_LEN];
248 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf),
249 &e->svbr_blk, B_TRUE);
250 (void) printf("\tERROR: %d unmatched FREE(s): %s\n",
251 e->svbr_refcnt, blkbuf);
253 zfs_btree_destroy(&sv->sv_pair);
255 return (err);
258 static int
259 livelist_block_compare(const void *larg, const void *rarg)
261 const sublivelist_verify_block_t *l = larg;
262 const sublivelist_verify_block_t *r = rarg;
264 if (DVA_GET_VDEV(&l->svb_dva) < DVA_GET_VDEV(&r->svb_dva))
265 return (-1);
266 else if (DVA_GET_VDEV(&l->svb_dva) > DVA_GET_VDEV(&r->svb_dva))
267 return (+1);
269 if (DVA_GET_OFFSET(&l->svb_dva) < DVA_GET_OFFSET(&r->svb_dva))
270 return (-1);
271 else if (DVA_GET_OFFSET(&l->svb_dva) > DVA_GET_OFFSET(&r->svb_dva))
272 return (+1);
274 if (DVA_GET_ASIZE(&l->svb_dva) < DVA_GET_ASIZE(&r->svb_dva))
275 return (-1);
276 else if (DVA_GET_ASIZE(&l->svb_dva) > DVA_GET_ASIZE(&r->svb_dva))
277 return (+1);
279 return (0);
283 * Check for errors in a livelist while tracking all unfreed ALLOCs in the
284 * sublivelist_verify_t: sv->sv_leftover
286 static void
287 livelist_verify(dsl_deadlist_t *dl, void *arg)
289 sublivelist_verify_t *sv = arg;
290 dsl_deadlist_iterate(dl, sublivelist_verify_func, sv);
294 * Check for errors in the livelist entry and discard the intermediary
295 * data structures
297 static int
298 sublivelist_verify_lightweight(void *args, dsl_deadlist_entry_t *dle)
300 (void) args;
301 sublivelist_verify_t sv;
302 zfs_btree_create(&sv.sv_leftover, livelist_block_compare, NULL,
303 sizeof (sublivelist_verify_block_t));
304 int err = sublivelist_verify_func(&sv, dle);
305 zfs_btree_clear(&sv.sv_leftover);
306 zfs_btree_destroy(&sv.sv_leftover);
307 return (err);
310 typedef struct metaslab_verify {
312 * Tree containing all the leftover ALLOCs from the livelists
313 * that are part of this metaslab.
315 zfs_btree_t mv_livelist_allocs;
318 * Metaslab information.
320 uint64_t mv_vdid;
321 uint64_t mv_msid;
322 uint64_t mv_start;
323 uint64_t mv_end;
326 * What's currently allocated for this metaslab.
328 range_tree_t *mv_allocated;
329 } metaslab_verify_t;
331 typedef void ll_iter_t(dsl_deadlist_t *ll, void *arg);
333 typedef int (*zdb_log_sm_cb_t)(spa_t *spa, space_map_entry_t *sme, uint64_t txg,
334 void *arg);
336 typedef struct unflushed_iter_cb_arg {
337 spa_t *uic_spa;
338 uint64_t uic_txg;
339 void *uic_arg;
340 zdb_log_sm_cb_t uic_cb;
341 } unflushed_iter_cb_arg_t;
343 static int
344 iterate_through_spacemap_logs_cb(space_map_entry_t *sme, void *arg)
346 unflushed_iter_cb_arg_t *uic = arg;
347 return (uic->uic_cb(uic->uic_spa, sme, uic->uic_txg, uic->uic_arg));
350 static void
351 iterate_through_spacemap_logs(spa_t *spa, zdb_log_sm_cb_t cb, void *arg)
353 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
354 return;
356 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
357 for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
358 sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls)) {
359 space_map_t *sm = NULL;
360 VERIFY0(space_map_open(&sm, spa_meta_objset(spa),
361 sls->sls_sm_obj, 0, UINT64_MAX, SPA_MINBLOCKSHIFT));
363 unflushed_iter_cb_arg_t uic = {
364 .uic_spa = spa,
365 .uic_txg = sls->sls_txg,
366 .uic_arg = arg,
367 .uic_cb = cb
369 VERIFY0(space_map_iterate(sm, space_map_length(sm),
370 iterate_through_spacemap_logs_cb, &uic));
371 space_map_close(sm);
373 spa_config_exit(spa, SCL_CONFIG, FTAG);
376 static void
377 verify_livelist_allocs(metaslab_verify_t *mv, uint64_t txg,
378 uint64_t offset, uint64_t size)
380 sublivelist_verify_block_t svb = {{{0}}};
381 DVA_SET_VDEV(&svb.svb_dva, mv->mv_vdid);
382 DVA_SET_OFFSET(&svb.svb_dva, offset);
383 DVA_SET_ASIZE(&svb.svb_dva, size);
384 zfs_btree_index_t where;
385 uint64_t end_offset = offset + size;
388 * Look for an exact match for spacemap entry in the livelist entries.
389 * Then, look for other livelist entries that fall within the range
390 * of the spacemap entry as it may have been condensed
392 sublivelist_verify_block_t *found =
393 zfs_btree_find(&mv->mv_livelist_allocs, &svb, &where);
394 if (found == NULL) {
395 found = zfs_btree_next(&mv->mv_livelist_allocs, &where, &where);
397 for (; found != NULL && DVA_GET_VDEV(&found->svb_dva) == mv->mv_vdid &&
398 DVA_GET_OFFSET(&found->svb_dva) < end_offset;
399 found = zfs_btree_next(&mv->mv_livelist_allocs, &where, &where)) {
400 if (found->svb_allocated_txg <= txg) {
401 (void) printf("ERROR: Livelist ALLOC [%llx:%llx] "
402 "from TXG %llx FREED at TXG %llx\n",
403 (u_longlong_t)DVA_GET_OFFSET(&found->svb_dva),
404 (u_longlong_t)DVA_GET_ASIZE(&found->svb_dva),
405 (u_longlong_t)found->svb_allocated_txg,
406 (u_longlong_t)txg);
411 static int
412 metaslab_spacemap_validation_cb(space_map_entry_t *sme, void *arg)
414 metaslab_verify_t *mv = arg;
415 uint64_t offset = sme->sme_offset;
416 uint64_t size = sme->sme_run;
417 uint64_t txg = sme->sme_txg;
419 if (sme->sme_type == SM_ALLOC) {
420 if (range_tree_contains(mv->mv_allocated,
421 offset, size)) {
422 (void) printf("ERROR: DOUBLE ALLOC: "
423 "%llu [%llx:%llx] "
424 "%llu:%llu LOG_SM\n",
425 (u_longlong_t)txg, (u_longlong_t)offset,
426 (u_longlong_t)size, (u_longlong_t)mv->mv_vdid,
427 (u_longlong_t)mv->mv_msid);
428 } else {
429 range_tree_add(mv->mv_allocated,
430 offset, size);
432 } else {
433 if (!range_tree_contains(mv->mv_allocated,
434 offset, size)) {
435 (void) printf("ERROR: DOUBLE FREE: "
436 "%llu [%llx:%llx] "
437 "%llu:%llu LOG_SM\n",
438 (u_longlong_t)txg, (u_longlong_t)offset,
439 (u_longlong_t)size, (u_longlong_t)mv->mv_vdid,
440 (u_longlong_t)mv->mv_msid);
441 } else {
442 range_tree_remove(mv->mv_allocated,
443 offset, size);
447 if (sme->sme_type != SM_ALLOC) {
449 * If something is freed in the spacemap, verify that
450 * it is not listed as allocated in the livelist.
452 verify_livelist_allocs(mv, txg, offset, size);
454 return (0);
457 static int
458 spacemap_check_sm_log_cb(spa_t *spa, space_map_entry_t *sme,
459 uint64_t txg, void *arg)
461 metaslab_verify_t *mv = arg;
462 uint64_t offset = sme->sme_offset;
463 uint64_t vdev_id = sme->sme_vdev;
465 vdev_t *vd = vdev_lookup_top(spa, vdev_id);
467 /* skip indirect vdevs */
468 if (!vdev_is_concrete(vd))
469 return (0);
471 if (vdev_id != mv->mv_vdid)
472 return (0);
474 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
475 if (ms->ms_id != mv->mv_msid)
476 return (0);
478 if (txg < metaslab_unflushed_txg(ms))
479 return (0);
482 ASSERT3U(txg, ==, sme->sme_txg);
483 return (metaslab_spacemap_validation_cb(sme, mv));
486 static void
487 spacemap_check_sm_log(spa_t *spa, metaslab_verify_t *mv)
489 iterate_through_spacemap_logs(spa, spacemap_check_sm_log_cb, mv);
492 static void
493 spacemap_check_ms_sm(space_map_t *sm, metaslab_verify_t *mv)
495 if (sm == NULL)
496 return;
498 VERIFY0(space_map_iterate(sm, space_map_length(sm),
499 metaslab_spacemap_validation_cb, mv));
502 static void iterate_deleted_livelists(spa_t *spa, ll_iter_t func, void *arg);
505 * Transfer blocks from sv_leftover tree to the mv_livelist_allocs if
506 * they are part of that metaslab (mv_msid).
508 static void
509 mv_populate_livelist_allocs(metaslab_verify_t *mv, sublivelist_verify_t *sv)
511 zfs_btree_index_t where;
512 sublivelist_verify_block_t *svb;
513 ASSERT3U(zfs_btree_numnodes(&mv->mv_livelist_allocs), ==, 0);
514 for (svb = zfs_btree_first(&sv->sv_leftover, &where);
515 svb != NULL;
516 svb = zfs_btree_next(&sv->sv_leftover, &where, &where)) {
517 if (DVA_GET_VDEV(&svb->svb_dva) != mv->mv_vdid)
518 continue;
520 if (DVA_GET_OFFSET(&svb->svb_dva) < mv->mv_start &&
521 (DVA_GET_OFFSET(&svb->svb_dva) +
522 DVA_GET_ASIZE(&svb->svb_dva)) > mv->mv_start) {
523 (void) printf("ERROR: Found block that crosses "
524 "metaslab boundary: <%llu:%llx:%llx>\n",
525 (u_longlong_t)DVA_GET_VDEV(&svb->svb_dva),
526 (u_longlong_t)DVA_GET_OFFSET(&svb->svb_dva),
527 (u_longlong_t)DVA_GET_ASIZE(&svb->svb_dva));
528 continue;
531 if (DVA_GET_OFFSET(&svb->svb_dva) < mv->mv_start)
532 continue;
534 if (DVA_GET_OFFSET(&svb->svb_dva) >= mv->mv_end)
535 continue;
537 if ((DVA_GET_OFFSET(&svb->svb_dva) +
538 DVA_GET_ASIZE(&svb->svb_dva)) > mv->mv_end) {
539 (void) printf("ERROR: Found block that crosses "
540 "metaslab boundary: <%llu:%llx:%llx>\n",
541 (u_longlong_t)DVA_GET_VDEV(&svb->svb_dva),
542 (u_longlong_t)DVA_GET_OFFSET(&svb->svb_dva),
543 (u_longlong_t)DVA_GET_ASIZE(&svb->svb_dva));
544 continue;
547 zfs_btree_add(&mv->mv_livelist_allocs, svb);
550 for (svb = zfs_btree_first(&mv->mv_livelist_allocs, &where);
551 svb != NULL;
552 svb = zfs_btree_next(&mv->mv_livelist_allocs, &where, &where)) {
553 zfs_btree_remove(&sv->sv_leftover, svb);
558 * [Livelist Check]
559 * Iterate through all the sublivelists and:
560 * - report leftover frees (**)
561 * - record leftover ALLOCs together with their TXG [see Cross Check]
563 * (**) Note: Double ALLOCs are valid in datasets that have dedup
564 * enabled. Similarly double FREEs are allowed as well but
565 * only if they pair up with a corresponding ALLOC entry once
566 * we our done with our sublivelist iteration.
568 * [Spacemap Check]
569 * for each metaslab:
570 * - iterate over spacemap and then the metaslab's entries in the
571 * spacemap log, then report any double FREEs and ALLOCs (do not
572 * blow up).
574 * [Cross Check]
575 * After finishing the Livelist Check phase and while being in the
576 * Spacemap Check phase, we find all the recorded leftover ALLOCs
577 * of the livelist check that are part of the metaslab that we are
578 * currently looking at in the Spacemap Check. We report any entries
579 * that are marked as ALLOCs in the livelists but have been actually
580 * freed (and potentially allocated again) after their TXG stamp in
581 * the spacemaps. Also report any ALLOCs from the livelists that
582 * belong to indirect vdevs (e.g. their vdev completed removal).
584 * Note that this will miss Log Spacemap entries that cancelled each other
585 * out before being flushed to the metaslab, so we are not guaranteed
586 * to match all erroneous ALLOCs.
588 static void
589 livelist_metaslab_validate(spa_t *spa)
591 (void) printf("Verifying deleted livelist entries\n");
593 sublivelist_verify_t sv;
594 zfs_btree_create(&sv.sv_leftover, livelist_block_compare, NULL,
595 sizeof (sublivelist_verify_block_t));
596 iterate_deleted_livelists(spa, livelist_verify, &sv);
598 (void) printf("Verifying metaslab entries\n");
599 vdev_t *rvd = spa->spa_root_vdev;
600 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
601 vdev_t *vd = rvd->vdev_child[c];
603 if (!vdev_is_concrete(vd))
604 continue;
606 for (uint64_t mid = 0; mid < vd->vdev_ms_count; mid++) {
607 metaslab_t *m = vd->vdev_ms[mid];
609 (void) fprintf(stderr,
610 "\rverifying concrete vdev %llu, "
611 "metaslab %llu of %llu ...",
612 (longlong_t)vd->vdev_id,
613 (longlong_t)mid,
614 (longlong_t)vd->vdev_ms_count);
616 uint64_t shift, start;
617 range_seg_type_t type =
618 metaslab_calculate_range_tree_type(vd, m,
619 &start, &shift);
620 metaslab_verify_t mv;
621 mv.mv_allocated = range_tree_create(NULL,
622 type, NULL, start, shift);
623 mv.mv_vdid = vd->vdev_id;
624 mv.mv_msid = m->ms_id;
625 mv.mv_start = m->ms_start;
626 mv.mv_end = m->ms_start + m->ms_size;
627 zfs_btree_create(&mv.mv_livelist_allocs,
628 livelist_block_compare, NULL,
629 sizeof (sublivelist_verify_block_t));
631 mv_populate_livelist_allocs(&mv, &sv);
633 spacemap_check_ms_sm(m->ms_sm, &mv);
634 spacemap_check_sm_log(spa, &mv);
636 range_tree_vacate(mv.mv_allocated, NULL, NULL);
637 range_tree_destroy(mv.mv_allocated);
638 zfs_btree_clear(&mv.mv_livelist_allocs);
639 zfs_btree_destroy(&mv.mv_livelist_allocs);
642 (void) fprintf(stderr, "\n");
645 * If there are any segments in the leftover tree after we walked
646 * through all the metaslabs in the concrete vdevs then this means
647 * that we have segments in the livelists that belong to indirect
648 * vdevs and are marked as allocated.
650 if (zfs_btree_numnodes(&sv.sv_leftover) == 0) {
651 zfs_btree_destroy(&sv.sv_leftover);
652 return;
654 (void) printf("ERROR: Found livelist blocks marked as allocated "
655 "for indirect vdevs:\n");
657 zfs_btree_index_t *where = NULL;
658 sublivelist_verify_block_t *svb;
659 while ((svb = zfs_btree_destroy_nodes(&sv.sv_leftover, &where)) !=
660 NULL) {
661 int vdev_id = DVA_GET_VDEV(&svb->svb_dva);
662 ASSERT3U(vdev_id, <, rvd->vdev_children);
663 vdev_t *vd = rvd->vdev_child[vdev_id];
664 ASSERT(!vdev_is_concrete(vd));
665 (void) printf("<%d:%llx:%llx> TXG %llx\n",
666 vdev_id, (u_longlong_t)DVA_GET_OFFSET(&svb->svb_dva),
667 (u_longlong_t)DVA_GET_ASIZE(&svb->svb_dva),
668 (u_longlong_t)svb->svb_allocated_txg);
670 (void) printf("\n");
671 zfs_btree_destroy(&sv.sv_leftover);
675 * These libumem hooks provide a reasonable set of defaults for the allocator's
676 * debugging facilities.
678 const char *
679 _umem_debug_init(void)
681 return ("default,verbose"); /* $UMEM_DEBUG setting */
684 const char *
685 _umem_logging_init(void)
687 return ("fail,contents"); /* $UMEM_LOGGING setting */
690 static void
691 usage(void)
693 (void) fprintf(stderr,
694 "Usage:\t%s [-AbcdDFGhikLMPsvXy] [-e [-V] [-p <path> ...]] "
695 "[-I <inflight I/Os>]\n"
696 "\t\t[-o <var>=<value>]... [-t <txg>] [-U <cache>] [-x <dumpdir>]\n"
697 "\t\t[-K <key>]\n"
698 "\t\t[<poolname>[/<dataset | objset id>] [<object | range> ...]]\n"
699 "\t%s [-AdiPv] [-e [-V] [-p <path> ...]] [-U <cache>] [-K <key>]\n"
700 "\t\t[<poolname>[/<dataset | objset id>] [<object | range> ...]\n"
701 "\t%s -B [-e [-V] [-p <path> ...]] [-I <inflight I/Os>]\n"
702 "\t\t[-o <var>=<value>]... [-t <txg>] [-U <cache>] [-x <dumpdir>]\n"
703 "\t\t[-K <key>] <poolname>/<objset id> [<backupflags>]\n"
704 "\t%s [-v] <bookmark>\n"
705 "\t%s -C [-A] [-U <cache>] [<poolname>]\n"
706 "\t%s -l [-Aqu] <device>\n"
707 "\t%s -m [-AFLPX] [-e [-V] [-p <path> ...]] [-t <txg>] "
708 "[-U <cache>]\n\t\t<poolname> [<vdev> [<metaslab> ...]]\n"
709 "\t%s -O [-K <key>] <dataset> <path>\n"
710 "\t%s -r [-K <key>] <dataset> <path> <destination>\n"
711 "\t%s -R [-A] [-e [-V] [-p <path> ...]] [-U <cache>]\n"
712 "\t\t<poolname> <vdev>:<offset>:<size>[:<flags>]\n"
713 "\t%s -E [-A] word0:word1:...:word15\n"
714 "\t%s -S [-AP] [-e [-V] [-p <path> ...]] [-U <cache>] "
715 "<poolname>\n\n",
716 cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname,
717 cmdname, cmdname, cmdname, cmdname, cmdname);
719 (void) fprintf(stderr, " Dataset name must include at least one "
720 "separator character '/' or '@'\n");
721 (void) fprintf(stderr, " If dataset name is specified, only that "
722 "dataset is dumped\n");
723 (void) fprintf(stderr, " If object numbers or object number "
724 "ranges are specified, only those\n"
725 " objects or ranges are dumped.\n\n");
726 (void) fprintf(stderr,
727 " Object ranges take the form <start>:<end>[:<flags>]\n"
728 " start Starting object number\n"
729 " end Ending object number, or -1 for no upper bound\n"
730 " flags Optional flags to select object types:\n"
731 " A All objects (this is the default)\n"
732 " d ZFS directories\n"
733 " f ZFS files \n"
734 " m SPA space maps\n"
735 " z ZAPs\n"
736 " - Negate effect of next flag\n\n");
737 (void) fprintf(stderr, " Options to control amount of output:\n");
738 (void) fprintf(stderr, " -b --block-stats "
739 "block statistics\n");
740 (void) fprintf(stderr, " -B --backup "
741 "backup stream\n");
742 (void) fprintf(stderr, " -c --checksum "
743 "checksum all metadata (twice for all data) blocks\n");
744 (void) fprintf(stderr, " -C --config "
745 "config (or cachefile if alone)\n");
746 (void) fprintf(stderr, " -d --datasets "
747 "dataset(s)\n");
748 (void) fprintf(stderr, " -D --dedup-stats "
749 "dedup statistics\n");
750 (void) fprintf(stderr, " -E --embedded-block-pointer=INTEGER\n"
751 " decode and display block "
752 "from an embedded block pointer\n");
753 (void) fprintf(stderr, " -h --history "
754 "pool history\n");
755 (void) fprintf(stderr, " -i --intent-logs "
756 "intent logs\n");
757 (void) fprintf(stderr, " -l --label "
758 "read label contents\n");
759 (void) fprintf(stderr, " -k --checkpointed-state "
760 "examine the checkpointed state of the pool\n");
761 (void) fprintf(stderr, " -L --disable-leak-tracking "
762 "disable leak tracking (do not load spacemaps)\n");
763 (void) fprintf(stderr, " -m --metaslabs "
764 "metaslabs\n");
765 (void) fprintf(stderr, " -M --metaslab-groups "
766 "metaslab groups\n");
767 (void) fprintf(stderr, " -O --object-lookups "
768 "perform object lookups by path\n");
769 (void) fprintf(stderr, " -r --copy-object "
770 "copy an object by path to file\n");
771 (void) fprintf(stderr, " -R --read-block "
772 "read and display block from a device\n");
773 (void) fprintf(stderr, " -s --io-stats "
774 "report stats on zdb's I/O\n");
775 (void) fprintf(stderr, " -S --simulate-dedup "
776 "simulate dedup to measure effect\n");
777 (void) fprintf(stderr, " -v --verbose "
778 "verbose (applies to all others)\n");
779 (void) fprintf(stderr, " -y --livelist "
780 "perform livelist and metaslab validation on any livelists being "
781 "deleted\n\n");
782 (void) fprintf(stderr, " Below options are intended for use "
783 "with other options:\n");
784 (void) fprintf(stderr, " -A --ignore-assertions "
785 "ignore assertions (-A), enable panic recovery (-AA) or both "
786 "(-AAA)\n");
787 (void) fprintf(stderr, " -e --exported "
788 "pool is exported/destroyed/has altroot/not in a cachefile\n");
789 (void) fprintf(stderr, " -F --automatic-rewind "
790 "attempt automatic rewind within safe range of transaction "
791 "groups\n");
792 (void) fprintf(stderr, " -G --dump-debug-msg "
793 "dump zfs_dbgmsg buffer before exiting\n");
794 (void) fprintf(stderr, " -I --inflight=INTEGER "
795 "specify the maximum number of checksumming I/Os "
796 "[default is 200]\n");
797 (void) fprintf(stderr, " -K --key=KEY "
798 "decryption key for encrypted dataset\n");
799 (void) fprintf(stderr, " -o --option=\"OPTION=INTEGER\" "
800 "set global variable to an unsigned 32-bit integer\n");
801 (void) fprintf(stderr, " -p --path==PATH "
802 "use one or more with -e to specify path to vdev dir\n");
803 (void) fprintf(stderr, " -P --parseable "
804 "print numbers in parseable form\n");
805 (void) fprintf(stderr, " -q --skip-label "
806 "don't print label contents\n");
807 (void) fprintf(stderr, " -t --txg=INTEGER "
808 "highest txg to use when searching for uberblocks\n");
809 (void) fprintf(stderr, " -T --brt-stats "
810 "BRT statistics\n");
811 (void) fprintf(stderr, " -u --uberblock "
812 "uberblock\n");
813 (void) fprintf(stderr, " -U --cachefile=PATH "
814 "use alternate cachefile\n");
815 (void) fprintf(stderr, " -V --verbatim "
816 "do verbatim import\n");
817 (void) fprintf(stderr, " -x --dump-blocks=PATH "
818 "dump all read blocks into specified directory\n");
819 (void) fprintf(stderr, " -X --extreme-rewind "
820 "attempt extreme rewind (does not work with dataset)\n");
821 (void) fprintf(stderr, " -Y --all-reconstruction "
822 "attempt all reconstruction combinations for split blocks\n");
823 (void) fprintf(stderr, " -Z --zstd-headers "
824 "show ZSTD headers \n");
825 (void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
826 "to make only that option verbose\n");
827 (void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
828 zdb_exit(1);
831 static void
832 dump_debug_buffer(void)
834 ssize_t ret __attribute__((unused));
836 if (!dump_opt['G'])
837 return;
839 * We use write() instead of printf() so that this function
840 * is safe to call from a signal handler.
842 ret = write(STDERR_FILENO, "\n", 1);
843 zfs_dbgmsg_print(STDERR_FILENO, "zdb");
846 static void sig_handler(int signo)
848 struct sigaction action;
850 libspl_backtrace(STDERR_FILENO);
851 dump_debug_buffer();
854 * Restore default action and re-raise signal so SIGSEGV and
855 * SIGABRT can trigger a core dump.
857 action.sa_handler = SIG_DFL;
858 sigemptyset(&action.sa_mask);
859 action.sa_flags = 0;
860 (void) sigaction(signo, &action, NULL);
861 raise(signo);
865 * Called for usage errors that are discovered after a call to spa_open(),
866 * dmu_bonus_hold(), or pool_match(). abort() is called for other errors.
869 static void
870 fatal(const char *fmt, ...)
872 va_list ap;
874 va_start(ap, fmt);
875 (void) fprintf(stderr, "%s: ", cmdname);
876 (void) vfprintf(stderr, fmt, ap);
877 va_end(ap);
878 (void) fprintf(stderr, "\n");
880 dump_debug_buffer();
882 zdb_exit(1);
885 static void
886 dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
888 (void) size;
889 nvlist_t *nv;
890 size_t nvsize = *(uint64_t *)data;
891 char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
893 VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
895 VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
897 umem_free(packed, nvsize);
899 dump_nvlist(nv, 8);
901 nvlist_free(nv);
904 static void
905 dump_history_offsets(objset_t *os, uint64_t object, void *data, size_t size)
907 (void) os, (void) object, (void) size;
908 spa_history_phys_t *shp = data;
910 if (shp == NULL)
911 return;
913 (void) printf("\t\tpool_create_len = %llu\n",
914 (u_longlong_t)shp->sh_pool_create_len);
915 (void) printf("\t\tphys_max_off = %llu\n",
916 (u_longlong_t)shp->sh_phys_max_off);
917 (void) printf("\t\tbof = %llu\n",
918 (u_longlong_t)shp->sh_bof);
919 (void) printf("\t\teof = %llu\n",
920 (u_longlong_t)shp->sh_eof);
921 (void) printf("\t\trecords_lost = %llu\n",
922 (u_longlong_t)shp->sh_records_lost);
925 static void
926 zdb_nicenum(uint64_t num, char *buf, size_t buflen)
928 if (dump_opt['P'])
929 (void) snprintf(buf, buflen, "%llu", (longlong_t)num);
930 else
931 nicenum(num, buf, buflen);
934 static void
935 zdb_nicebytes(uint64_t bytes, char *buf, size_t buflen)
937 if (dump_opt['P'])
938 (void) snprintf(buf, buflen, "%llu", (longlong_t)bytes);
939 else
940 zfs_nicebytes(bytes, buf, buflen);
943 static const char histo_stars[] = "****************************************";
944 static const uint64_t histo_width = sizeof (histo_stars) - 1;
946 static void
947 dump_histogram(const uint64_t *histo, int size, int offset)
949 int i;
950 int minidx = size - 1;
951 int maxidx = 0;
952 uint64_t max = 0;
954 for (i = 0; i < size; i++) {
955 if (histo[i] == 0)
956 continue;
957 if (histo[i] > max)
958 max = histo[i];
959 if (i > maxidx)
960 maxidx = i;
961 if (i < minidx)
962 minidx = i;
965 if (max < histo_width)
966 max = histo_width;
968 for (i = minidx; i <= maxidx; i++) {
969 (void) printf("\t\t\t%3u: %6llu %s\n",
970 i + offset, (u_longlong_t)histo[i],
971 &histo_stars[(max - histo[i]) * histo_width / max]);
975 static void
976 dump_zap_stats(objset_t *os, uint64_t object)
978 int error;
979 zap_stats_t zs;
981 error = zap_get_stats(os, object, &zs);
982 if (error)
983 return;
985 if (zs.zs_ptrtbl_len == 0) {
986 ASSERT(zs.zs_num_blocks == 1);
987 (void) printf("\tmicrozap: %llu bytes, %llu entries\n",
988 (u_longlong_t)zs.zs_blocksize,
989 (u_longlong_t)zs.zs_num_entries);
990 return;
993 (void) printf("\tFat ZAP stats:\n");
995 (void) printf("\t\tPointer table:\n");
996 (void) printf("\t\t\t%llu elements\n",
997 (u_longlong_t)zs.zs_ptrtbl_len);
998 (void) printf("\t\t\tzt_blk: %llu\n",
999 (u_longlong_t)zs.zs_ptrtbl_zt_blk);
1000 (void) printf("\t\t\tzt_numblks: %llu\n",
1001 (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
1002 (void) printf("\t\t\tzt_shift: %llu\n",
1003 (u_longlong_t)zs.zs_ptrtbl_zt_shift);
1004 (void) printf("\t\t\tzt_blks_copied: %llu\n",
1005 (u_longlong_t)zs.zs_ptrtbl_blks_copied);
1006 (void) printf("\t\t\tzt_nextblk: %llu\n",
1007 (u_longlong_t)zs.zs_ptrtbl_nextblk);
1009 (void) printf("\t\tZAP entries: %llu\n",
1010 (u_longlong_t)zs.zs_num_entries);
1011 (void) printf("\t\tLeaf blocks: %llu\n",
1012 (u_longlong_t)zs.zs_num_leafs);
1013 (void) printf("\t\tTotal blocks: %llu\n",
1014 (u_longlong_t)zs.zs_num_blocks);
1015 (void) printf("\t\tzap_block_type: 0x%llx\n",
1016 (u_longlong_t)zs.zs_block_type);
1017 (void) printf("\t\tzap_magic: 0x%llx\n",
1018 (u_longlong_t)zs.zs_magic);
1019 (void) printf("\t\tzap_salt: 0x%llx\n",
1020 (u_longlong_t)zs.zs_salt);
1022 (void) printf("\t\tLeafs with 2^n pointers:\n");
1023 dump_histogram(zs.zs_leafs_with_2n_pointers, ZAP_HISTOGRAM_SIZE, 0);
1025 (void) printf("\t\tBlocks with n*5 entries:\n");
1026 dump_histogram(zs.zs_blocks_with_n5_entries, ZAP_HISTOGRAM_SIZE, 0);
1028 (void) printf("\t\tBlocks n/10 full:\n");
1029 dump_histogram(zs.zs_blocks_n_tenths_full, ZAP_HISTOGRAM_SIZE, 0);
1031 (void) printf("\t\tEntries with n chunks:\n");
1032 dump_histogram(zs.zs_entries_using_n_chunks, ZAP_HISTOGRAM_SIZE, 0);
1034 (void) printf("\t\tBuckets with n entries:\n");
1035 dump_histogram(zs.zs_buckets_with_n_entries, ZAP_HISTOGRAM_SIZE, 0);
1038 static void
1039 dump_none(objset_t *os, uint64_t object, void *data, size_t size)
1041 (void) os, (void) object, (void) data, (void) size;
1044 static void
1045 dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
1047 (void) os, (void) object, (void) data, (void) size;
1048 (void) printf("\tUNKNOWN OBJECT TYPE\n");
1051 static void
1052 dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
1054 (void) os, (void) object, (void) data, (void) size;
1057 static void
1058 dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
1060 uint64_t *arr;
1061 uint64_t oursize;
1062 if (dump_opt['d'] < 6)
1063 return;
1065 if (data == NULL) {
1066 dmu_object_info_t doi;
1068 VERIFY0(dmu_object_info(os, object, &doi));
1069 size = doi.doi_max_offset;
1071 * We cap the size at 1 mebibyte here to prevent
1072 * allocation failures and nigh-infinite printing if the
1073 * object is extremely large.
1075 oursize = MIN(size, 1 << 20);
1076 arr = kmem_alloc(oursize, KM_SLEEP);
1078 int err = dmu_read(os, object, 0, oursize, arr, 0);
1079 if (err != 0) {
1080 (void) printf("got error %u from dmu_read\n", err);
1081 kmem_free(arr, oursize);
1082 return;
1084 } else {
1086 * Even though the allocation is already done in this code path,
1087 * we still cap the size to prevent excessive printing.
1089 oursize = MIN(size, 1 << 20);
1090 arr = data;
1093 if (size == 0) {
1094 if (data == NULL)
1095 kmem_free(arr, oursize);
1096 (void) printf("\t\t[]\n");
1097 return;
1100 (void) printf("\t\t[%0llx", (u_longlong_t)arr[0]);
1101 for (size_t i = 1; i * sizeof (uint64_t) < oursize; i++) {
1102 if (i % 4 != 0)
1103 (void) printf(", %0llx", (u_longlong_t)arr[i]);
1104 else
1105 (void) printf(",\n\t\t%0llx", (u_longlong_t)arr[i]);
1107 if (oursize != size)
1108 (void) printf(", ... ");
1109 (void) printf("]\n");
1111 if (data == NULL)
1112 kmem_free(arr, oursize);
1115 static void
1116 dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
1118 (void) data, (void) size;
1119 zap_cursor_t zc;
1120 zap_attribute_t *attrp = zap_attribute_long_alloc();
1121 void *prop;
1122 unsigned i;
1124 dump_zap_stats(os, object);
1125 (void) printf("\n");
1127 for (zap_cursor_init(&zc, os, object);
1128 zap_cursor_retrieve(&zc, attrp) == 0;
1129 zap_cursor_advance(&zc)) {
1130 boolean_t key64 =
1131 !!(zap_getflags(zc.zc_zap) & ZAP_FLAG_UINT64_KEY);
1133 if (key64)
1134 (void) printf("\t\t0x%010" PRIu64 "x = ",
1135 *(uint64_t *)attrp->za_name);
1136 else
1137 (void) printf("\t\t%s = ", attrp->za_name);
1139 if (attrp->za_num_integers == 0) {
1140 (void) printf("\n");
1141 continue;
1143 prop = umem_zalloc(attrp->za_num_integers *
1144 attrp->za_integer_length, UMEM_NOFAIL);
1146 if (key64)
1147 (void) zap_lookup_uint64(os, object,
1148 (const uint64_t *)attrp->za_name, 1,
1149 attrp->za_integer_length, attrp->za_num_integers,
1150 prop);
1151 else
1152 (void) zap_lookup(os, object, attrp->za_name,
1153 attrp->za_integer_length, attrp->za_num_integers,
1154 prop);
1156 if (attrp->za_integer_length == 1 && !key64) {
1157 if (strcmp(attrp->za_name,
1158 DSL_CRYPTO_KEY_MASTER_KEY) == 0 ||
1159 strcmp(attrp->za_name,
1160 DSL_CRYPTO_KEY_HMAC_KEY) == 0 ||
1161 strcmp(attrp->za_name, DSL_CRYPTO_KEY_IV) == 0 ||
1162 strcmp(attrp->za_name, DSL_CRYPTO_KEY_MAC) == 0 ||
1163 strcmp(attrp->za_name,
1164 DMU_POOL_CHECKSUM_SALT) == 0) {
1165 uint8_t *u8 = prop;
1167 for (i = 0; i < attrp->za_num_integers; i++) {
1168 (void) printf("%02x", u8[i]);
1170 } else {
1171 (void) printf("%s", (char *)prop);
1173 } else {
1174 for (i = 0; i < attrp->za_num_integers; i++) {
1175 switch (attrp->za_integer_length) {
1176 case 1:
1177 (void) printf("%u ",
1178 ((uint8_t *)prop)[i]);
1179 break;
1180 case 2:
1181 (void) printf("%u ",
1182 ((uint16_t *)prop)[i]);
1183 break;
1184 case 4:
1185 (void) printf("%u ",
1186 ((uint32_t *)prop)[i]);
1187 break;
1188 case 8:
1189 (void) printf("%lld ",
1190 (u_longlong_t)((int64_t *)prop)[i]);
1191 break;
1195 (void) printf("\n");
1196 umem_free(prop,
1197 attrp->za_num_integers * attrp->za_integer_length);
1199 zap_cursor_fini(&zc);
1200 zap_attribute_free(attrp);
1203 static void
1204 dump_bpobj(objset_t *os, uint64_t object, void *data, size_t size)
1206 bpobj_phys_t *bpop = data;
1207 uint64_t i;
1208 char bytes[32], comp[32], uncomp[32];
1210 /* make sure the output won't get truncated */
1211 _Static_assert(sizeof (bytes) >= NN_NUMBUF_SZ, "bytes truncated");
1212 _Static_assert(sizeof (comp) >= NN_NUMBUF_SZ, "comp truncated");
1213 _Static_assert(sizeof (uncomp) >= NN_NUMBUF_SZ, "uncomp truncated");
1215 if (bpop == NULL)
1216 return;
1218 zdb_nicenum(bpop->bpo_bytes, bytes, sizeof (bytes));
1219 zdb_nicenum(bpop->bpo_comp, comp, sizeof (comp));
1220 zdb_nicenum(bpop->bpo_uncomp, uncomp, sizeof (uncomp));
1222 (void) printf("\t\tnum_blkptrs = %llu\n",
1223 (u_longlong_t)bpop->bpo_num_blkptrs);
1224 (void) printf("\t\tbytes = %s\n", bytes);
1225 if (size >= BPOBJ_SIZE_V1) {
1226 (void) printf("\t\tcomp = %s\n", comp);
1227 (void) printf("\t\tuncomp = %s\n", uncomp);
1229 if (size >= BPOBJ_SIZE_V2) {
1230 (void) printf("\t\tsubobjs = %llu\n",
1231 (u_longlong_t)bpop->bpo_subobjs);
1232 (void) printf("\t\tnum_subobjs = %llu\n",
1233 (u_longlong_t)bpop->bpo_num_subobjs);
1235 if (size >= sizeof (*bpop)) {
1236 (void) printf("\t\tnum_freed = %llu\n",
1237 (u_longlong_t)bpop->bpo_num_freed);
1240 if (dump_opt['d'] < 5)
1241 return;
1243 for (i = 0; i < bpop->bpo_num_blkptrs; i++) {
1244 char blkbuf[BP_SPRINTF_LEN];
1245 blkptr_t bp;
1247 int err = dmu_read(os, object,
1248 i * sizeof (bp), sizeof (bp), &bp, 0);
1249 if (err != 0) {
1250 (void) printf("got error %u from dmu_read\n", err);
1251 break;
1253 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), &bp,
1254 BP_GET_FREE(&bp));
1255 (void) printf("\t%s\n", blkbuf);
1259 static void
1260 dump_bpobj_subobjs(objset_t *os, uint64_t object, void *data, size_t size)
1262 (void) data, (void) size;
1263 dmu_object_info_t doi;
1264 int64_t i;
1266 VERIFY0(dmu_object_info(os, object, &doi));
1267 uint64_t *subobjs = kmem_alloc(doi.doi_max_offset, KM_SLEEP);
1269 int err = dmu_read(os, object, 0, doi.doi_max_offset, subobjs, 0);
1270 if (err != 0) {
1271 (void) printf("got error %u from dmu_read\n", err);
1272 kmem_free(subobjs, doi.doi_max_offset);
1273 return;
1276 int64_t last_nonzero = -1;
1277 for (i = 0; i < doi.doi_max_offset / 8; i++) {
1278 if (subobjs[i] != 0)
1279 last_nonzero = i;
1282 for (i = 0; i <= last_nonzero; i++) {
1283 (void) printf("\t%llu\n", (u_longlong_t)subobjs[i]);
1285 kmem_free(subobjs, doi.doi_max_offset);
1288 static void
1289 dump_ddt_zap(objset_t *os, uint64_t object, void *data, size_t size)
1291 (void) data, (void) size;
1292 dump_zap_stats(os, object);
1293 /* contents are printed elsewhere, properly decoded */
1296 static void
1297 dump_sa_attrs(objset_t *os, uint64_t object, void *data, size_t size)
1299 (void) data, (void) size;
1300 zap_cursor_t zc;
1301 zap_attribute_t *attrp = zap_attribute_alloc();
1303 dump_zap_stats(os, object);
1304 (void) printf("\n");
1306 for (zap_cursor_init(&zc, os, object);
1307 zap_cursor_retrieve(&zc, attrp) == 0;
1308 zap_cursor_advance(&zc)) {
1309 (void) printf("\t\t%s = ", attrp->za_name);
1310 if (attrp->za_num_integers == 0) {
1311 (void) printf("\n");
1312 continue;
1314 (void) printf(" %llx : [%d:%d:%d]\n",
1315 (u_longlong_t)attrp->za_first_integer,
1316 (int)ATTR_LENGTH(attrp->za_first_integer),
1317 (int)ATTR_BSWAP(attrp->za_first_integer),
1318 (int)ATTR_NUM(attrp->za_first_integer));
1320 zap_cursor_fini(&zc);
1321 zap_attribute_free(attrp);
1324 static void
1325 dump_sa_layouts(objset_t *os, uint64_t object, void *data, size_t size)
1327 (void) data, (void) size;
1328 zap_cursor_t zc;
1329 zap_attribute_t *attrp = zap_attribute_alloc();
1330 uint16_t *layout_attrs;
1331 unsigned i;
1333 dump_zap_stats(os, object);
1334 (void) printf("\n");
1336 for (zap_cursor_init(&zc, os, object);
1337 zap_cursor_retrieve(&zc, attrp) == 0;
1338 zap_cursor_advance(&zc)) {
1339 (void) printf("\t\t%s = [", attrp->za_name);
1340 if (attrp->za_num_integers == 0) {
1341 (void) printf("\n");
1342 continue;
1345 VERIFY(attrp->za_integer_length == 2);
1346 layout_attrs = umem_zalloc(attrp->za_num_integers *
1347 attrp->za_integer_length, UMEM_NOFAIL);
1349 VERIFY(zap_lookup(os, object, attrp->za_name,
1350 attrp->za_integer_length,
1351 attrp->za_num_integers, layout_attrs) == 0);
1353 for (i = 0; i != attrp->za_num_integers; i++)
1354 (void) printf(" %d ", (int)layout_attrs[i]);
1355 (void) printf("]\n");
1356 umem_free(layout_attrs,
1357 attrp->za_num_integers * attrp->za_integer_length);
1359 zap_cursor_fini(&zc);
1360 zap_attribute_free(attrp);
1363 static void
1364 dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
1366 (void) data, (void) size;
1367 zap_cursor_t zc;
1368 zap_attribute_t *attrp = zap_attribute_long_alloc();
1369 const char *typenames[] = {
1370 /* 0 */ "not specified",
1371 /* 1 */ "FIFO",
1372 /* 2 */ "Character Device",
1373 /* 3 */ "3 (invalid)",
1374 /* 4 */ "Directory",
1375 /* 5 */ "5 (invalid)",
1376 /* 6 */ "Block Device",
1377 /* 7 */ "7 (invalid)",
1378 /* 8 */ "Regular File",
1379 /* 9 */ "9 (invalid)",
1380 /* 10 */ "Symbolic Link",
1381 /* 11 */ "11 (invalid)",
1382 /* 12 */ "Socket",
1383 /* 13 */ "Door",
1384 /* 14 */ "Event Port",
1385 /* 15 */ "15 (invalid)",
1388 dump_zap_stats(os, object);
1389 (void) printf("\n");
1391 for (zap_cursor_init(&zc, os, object);
1392 zap_cursor_retrieve(&zc, attrp) == 0;
1393 zap_cursor_advance(&zc)) {
1394 (void) printf("\t\t%s = %lld (type: %s)\n",
1395 attrp->za_name, ZFS_DIRENT_OBJ(attrp->za_first_integer),
1396 typenames[ZFS_DIRENT_TYPE(attrp->za_first_integer)]);
1398 zap_cursor_fini(&zc);
1399 zap_attribute_free(attrp);
1402 static int
1403 get_dtl_refcount(vdev_t *vd)
1405 int refcount = 0;
1407 if (vd->vdev_ops->vdev_op_leaf) {
1408 space_map_t *sm = vd->vdev_dtl_sm;
1410 if (sm != NULL &&
1411 sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
1412 return (1);
1413 return (0);
1416 for (unsigned c = 0; c < vd->vdev_children; c++)
1417 refcount += get_dtl_refcount(vd->vdev_child[c]);
1418 return (refcount);
1421 static int
1422 get_metaslab_refcount(vdev_t *vd)
1424 int refcount = 0;
1426 if (vd->vdev_top == vd) {
1427 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
1428 space_map_t *sm = vd->vdev_ms[m]->ms_sm;
1430 if (sm != NULL &&
1431 sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
1432 refcount++;
1435 for (unsigned c = 0; c < vd->vdev_children; c++)
1436 refcount += get_metaslab_refcount(vd->vdev_child[c]);
1438 return (refcount);
1441 static int
1442 get_obsolete_refcount(vdev_t *vd)
1444 uint64_t obsolete_sm_object;
1445 int refcount = 0;
1447 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
1448 if (vd->vdev_top == vd && obsolete_sm_object != 0) {
1449 dmu_object_info_t doi;
1450 VERIFY0(dmu_object_info(vd->vdev_spa->spa_meta_objset,
1451 obsolete_sm_object, &doi));
1452 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
1453 refcount++;
1455 } else {
1456 ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
1457 ASSERT3U(obsolete_sm_object, ==, 0);
1459 for (unsigned c = 0; c < vd->vdev_children; c++) {
1460 refcount += get_obsolete_refcount(vd->vdev_child[c]);
1463 return (refcount);
1466 static int
1467 get_prev_obsolete_spacemap_refcount(spa_t *spa)
1469 uint64_t prev_obj =
1470 spa->spa_condensing_indirect_phys.scip_prev_obsolete_sm_object;
1471 if (prev_obj != 0) {
1472 dmu_object_info_t doi;
1473 VERIFY0(dmu_object_info(spa->spa_meta_objset, prev_obj, &doi));
1474 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
1475 return (1);
1478 return (0);
1481 static int
1482 get_checkpoint_refcount(vdev_t *vd)
1484 int refcount = 0;
1486 if (vd->vdev_top == vd && vd->vdev_top_zap != 0 &&
1487 zap_contains(spa_meta_objset(vd->vdev_spa),
1488 vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) == 0)
1489 refcount++;
1491 for (uint64_t c = 0; c < vd->vdev_children; c++)
1492 refcount += get_checkpoint_refcount(vd->vdev_child[c]);
1494 return (refcount);
1497 static int
1498 get_log_spacemap_refcount(spa_t *spa)
1500 return (avl_numnodes(&spa->spa_sm_logs_by_txg));
1503 static int
1504 verify_spacemap_refcounts(spa_t *spa)
1506 uint64_t expected_refcount = 0;
1507 uint64_t actual_refcount;
1509 (void) feature_get_refcount(spa,
1510 &spa_feature_table[SPA_FEATURE_SPACEMAP_HISTOGRAM],
1511 &expected_refcount);
1512 actual_refcount = get_dtl_refcount(spa->spa_root_vdev);
1513 actual_refcount += get_metaslab_refcount(spa->spa_root_vdev);
1514 actual_refcount += get_obsolete_refcount(spa->spa_root_vdev);
1515 actual_refcount += get_prev_obsolete_spacemap_refcount(spa);
1516 actual_refcount += get_checkpoint_refcount(spa->spa_root_vdev);
1517 actual_refcount += get_log_spacemap_refcount(spa);
1519 if (expected_refcount != actual_refcount) {
1520 (void) printf("space map refcount mismatch: expected %lld != "
1521 "actual %lld\n",
1522 (longlong_t)expected_refcount,
1523 (longlong_t)actual_refcount);
1524 return (2);
1526 return (0);
1529 static void
1530 dump_spacemap(objset_t *os, space_map_t *sm)
1532 const char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
1533 "INVALID", "INVALID", "INVALID", "INVALID" };
1535 if (sm == NULL)
1536 return;
1538 (void) printf("space map object %llu:\n",
1539 (longlong_t)sm->sm_object);
1540 (void) printf(" smp_length = 0x%llx\n",
1541 (longlong_t)sm->sm_phys->smp_length);
1542 (void) printf(" smp_alloc = 0x%llx\n",
1543 (longlong_t)sm->sm_phys->smp_alloc);
1545 if (dump_opt['d'] < 6 && dump_opt['m'] < 4)
1546 return;
1549 * Print out the freelist entries in both encoded and decoded form.
1551 uint8_t mapshift = sm->sm_shift;
1552 int64_t alloc = 0;
1553 uint64_t word, entry_id = 0;
1554 for (uint64_t offset = 0; offset < space_map_length(sm);
1555 offset += sizeof (word)) {
1557 VERIFY0(dmu_read(os, space_map_object(sm), offset,
1558 sizeof (word), &word, DMU_READ_PREFETCH));
1560 if (sm_entry_is_debug(word)) {
1561 uint64_t de_txg = SM_DEBUG_TXG_DECODE(word);
1562 uint64_t de_sync_pass = SM_DEBUG_SYNCPASS_DECODE(word);
1563 if (de_txg == 0) {
1564 (void) printf(
1565 "\t [%6llu] PADDING\n",
1566 (u_longlong_t)entry_id);
1567 } else {
1568 (void) printf(
1569 "\t [%6llu] %s: txg %llu pass %llu\n",
1570 (u_longlong_t)entry_id,
1571 ddata[SM_DEBUG_ACTION_DECODE(word)],
1572 (u_longlong_t)de_txg,
1573 (u_longlong_t)de_sync_pass);
1575 entry_id++;
1576 continue;
1579 uint8_t words;
1580 char entry_type;
1581 uint64_t entry_off, entry_run, entry_vdev = SM_NO_VDEVID;
1583 if (sm_entry_is_single_word(word)) {
1584 entry_type = (SM_TYPE_DECODE(word) == SM_ALLOC) ?
1585 'A' : 'F';
1586 entry_off = (SM_OFFSET_DECODE(word) << mapshift) +
1587 sm->sm_start;
1588 entry_run = SM_RUN_DECODE(word) << mapshift;
1589 words = 1;
1590 } else {
1591 /* it is a two-word entry so we read another word */
1592 ASSERT(sm_entry_is_double_word(word));
1594 uint64_t extra_word;
1595 offset += sizeof (extra_word);
1596 VERIFY0(dmu_read(os, space_map_object(sm), offset,
1597 sizeof (extra_word), &extra_word,
1598 DMU_READ_PREFETCH));
1600 ASSERT3U(offset, <=, space_map_length(sm));
1602 entry_run = SM2_RUN_DECODE(word) << mapshift;
1603 entry_vdev = SM2_VDEV_DECODE(word);
1604 entry_type = (SM2_TYPE_DECODE(extra_word) == SM_ALLOC) ?
1605 'A' : 'F';
1606 entry_off = (SM2_OFFSET_DECODE(extra_word) <<
1607 mapshift) + sm->sm_start;
1608 words = 2;
1611 (void) printf("\t [%6llu] %c range:"
1612 " %010llx-%010llx size: %06llx vdev: %06llu words: %u\n",
1613 (u_longlong_t)entry_id,
1614 entry_type, (u_longlong_t)entry_off,
1615 (u_longlong_t)(entry_off + entry_run),
1616 (u_longlong_t)entry_run,
1617 (u_longlong_t)entry_vdev, words);
1619 if (entry_type == 'A')
1620 alloc += entry_run;
1621 else
1622 alloc -= entry_run;
1623 entry_id++;
1625 if (alloc != space_map_allocated(sm)) {
1626 (void) printf("space_map_object alloc (%lld) INCONSISTENT "
1627 "with space map summary (%lld)\n",
1628 (longlong_t)space_map_allocated(sm), (longlong_t)alloc);
1632 static void
1633 dump_metaslab_stats(metaslab_t *msp)
1635 char maxbuf[32];
1636 range_tree_t *rt = msp->ms_allocatable;
1637 zfs_btree_t *t = &msp->ms_allocatable_by_size;
1638 int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
1640 /* max sure nicenum has enough space */
1641 _Static_assert(sizeof (maxbuf) >= NN_NUMBUF_SZ, "maxbuf truncated");
1643 zdb_nicenum(metaslab_largest_allocatable(msp), maxbuf, sizeof (maxbuf));
1645 (void) printf("\t %25s %10lu %7s %6s %4s %4d%%\n",
1646 "segments", zfs_btree_numnodes(t), "maxsize", maxbuf,
1647 "freepct", free_pct);
1648 (void) printf("\tIn-memory histogram:\n");
1649 dump_histogram(rt->rt_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1652 static void
1653 dump_metaslab(metaslab_t *msp)
1655 vdev_t *vd = msp->ms_group->mg_vd;
1656 spa_t *spa = vd->vdev_spa;
1657 space_map_t *sm = msp->ms_sm;
1658 char freebuf[32];
1660 zdb_nicenum(msp->ms_size - space_map_allocated(sm), freebuf,
1661 sizeof (freebuf));
1663 (void) printf(
1664 "\tmetaslab %6llu offset %12llx spacemap %6llu free %5s\n",
1665 (u_longlong_t)msp->ms_id, (u_longlong_t)msp->ms_start,
1666 (u_longlong_t)space_map_object(sm), freebuf);
1668 if (dump_opt['m'] > 2 && !dump_opt['L']) {
1669 mutex_enter(&msp->ms_lock);
1670 VERIFY0(metaslab_load(msp));
1671 range_tree_stat_verify(msp->ms_allocatable);
1672 dump_metaslab_stats(msp);
1673 metaslab_unload(msp);
1674 mutex_exit(&msp->ms_lock);
1677 if (dump_opt['m'] > 1 && sm != NULL &&
1678 spa_feature_is_active(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
1680 * The space map histogram represents free space in chunks
1681 * of sm_shift (i.e. bucket 0 refers to 2^sm_shift).
1683 (void) printf("\tOn-disk histogram:\t\tfragmentation %llu\n",
1684 (u_longlong_t)msp->ms_fragmentation);
1685 dump_histogram(sm->sm_phys->smp_histogram,
1686 SPACE_MAP_HISTOGRAM_SIZE, sm->sm_shift);
1689 if (vd->vdev_ops == &vdev_draid_ops)
1690 ASSERT3U(msp->ms_size, <=, 1ULL << vd->vdev_ms_shift);
1691 else
1692 ASSERT3U(msp->ms_size, ==, 1ULL << vd->vdev_ms_shift);
1694 dump_spacemap(spa->spa_meta_objset, msp->ms_sm);
1696 if (spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP)) {
1697 (void) printf("\tFlush data:\n\tunflushed txg=%llu\n\n",
1698 (u_longlong_t)metaslab_unflushed_txg(msp));
1702 static void
1703 print_vdev_metaslab_header(vdev_t *vd)
1705 vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
1706 const char *bias_str = "";
1707 if (alloc_bias == VDEV_BIAS_LOG || vd->vdev_islog) {
1708 bias_str = VDEV_ALLOC_BIAS_LOG;
1709 } else if (alloc_bias == VDEV_BIAS_SPECIAL) {
1710 bias_str = VDEV_ALLOC_BIAS_SPECIAL;
1711 } else if (alloc_bias == VDEV_BIAS_DEDUP) {
1712 bias_str = VDEV_ALLOC_BIAS_DEDUP;
1715 uint64_t ms_flush_data_obj = 0;
1716 if (vd->vdev_top_zap != 0) {
1717 int error = zap_lookup(spa_meta_objset(vd->vdev_spa),
1718 vd->vdev_top_zap, VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS,
1719 sizeof (uint64_t), 1, &ms_flush_data_obj);
1720 if (error != ENOENT) {
1721 ASSERT0(error);
1725 (void) printf("\tvdev %10llu %s",
1726 (u_longlong_t)vd->vdev_id, bias_str);
1728 if (ms_flush_data_obj != 0) {
1729 (void) printf(" ms_unflushed_phys object %llu",
1730 (u_longlong_t)ms_flush_data_obj);
1733 (void) printf("\n\t%-10s%5llu %-19s %-15s %-12s\n",
1734 "metaslabs", (u_longlong_t)vd->vdev_ms_count,
1735 "offset", "spacemap", "free");
1736 (void) printf("\t%15s %19s %15s %12s\n",
1737 "---------------", "-------------------",
1738 "---------------", "------------");
1741 static void
1742 dump_metaslab_groups(spa_t *spa, boolean_t show_special)
1744 vdev_t *rvd = spa->spa_root_vdev;
1745 metaslab_class_t *mc = spa_normal_class(spa);
1746 metaslab_class_t *smc = spa_special_class(spa);
1747 uint64_t fragmentation;
1749 metaslab_class_histogram_verify(mc);
1751 for (unsigned c = 0; c < rvd->vdev_children; c++) {
1752 vdev_t *tvd = rvd->vdev_child[c];
1753 metaslab_group_t *mg = tvd->vdev_mg;
1755 if (mg == NULL || (mg->mg_class != mc &&
1756 (!show_special || mg->mg_class != smc)))
1757 continue;
1759 metaslab_group_histogram_verify(mg);
1760 mg->mg_fragmentation = metaslab_group_fragmentation(mg);
1762 (void) printf("\tvdev %10llu\t\tmetaslabs%5llu\t\t"
1763 "fragmentation",
1764 (u_longlong_t)tvd->vdev_id,
1765 (u_longlong_t)tvd->vdev_ms_count);
1766 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
1767 (void) printf("%3s\n", "-");
1768 } else {
1769 (void) printf("%3llu%%\n",
1770 (u_longlong_t)mg->mg_fragmentation);
1772 dump_histogram(mg->mg_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1775 (void) printf("\tpool %s\tfragmentation", spa_name(spa));
1776 fragmentation = metaslab_class_fragmentation(mc);
1777 if (fragmentation == ZFS_FRAG_INVALID)
1778 (void) printf("\t%3s\n", "-");
1779 else
1780 (void) printf("\t%3llu%%\n", (u_longlong_t)fragmentation);
1781 dump_histogram(mc->mc_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1784 static void
1785 print_vdev_indirect(vdev_t *vd)
1787 vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
1788 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
1789 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
1791 if (vim == NULL) {
1792 ASSERT3P(vib, ==, NULL);
1793 return;
1796 ASSERT3U(vdev_indirect_mapping_object(vim), ==,
1797 vic->vic_mapping_object);
1798 ASSERT3U(vdev_indirect_births_object(vib), ==,
1799 vic->vic_births_object);
1801 (void) printf("indirect births obj %llu:\n",
1802 (longlong_t)vic->vic_births_object);
1803 (void) printf(" vib_count = %llu\n",
1804 (longlong_t)vdev_indirect_births_count(vib));
1805 for (uint64_t i = 0; i < vdev_indirect_births_count(vib); i++) {
1806 vdev_indirect_birth_entry_phys_t *cur_vibe =
1807 &vib->vib_entries[i];
1808 (void) printf("\toffset %llx -> txg %llu\n",
1809 (longlong_t)cur_vibe->vibe_offset,
1810 (longlong_t)cur_vibe->vibe_phys_birth_txg);
1812 (void) printf("\n");
1814 (void) printf("indirect mapping obj %llu:\n",
1815 (longlong_t)vic->vic_mapping_object);
1816 (void) printf(" vim_max_offset = 0x%llx\n",
1817 (longlong_t)vdev_indirect_mapping_max_offset(vim));
1818 (void) printf(" vim_bytes_mapped = 0x%llx\n",
1819 (longlong_t)vdev_indirect_mapping_bytes_mapped(vim));
1820 (void) printf(" vim_count = %llu\n",
1821 (longlong_t)vdev_indirect_mapping_num_entries(vim));
1823 if (dump_opt['d'] <= 5 && dump_opt['m'] <= 3)
1824 return;
1826 uint32_t *counts = vdev_indirect_mapping_load_obsolete_counts(vim);
1828 for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
1829 vdev_indirect_mapping_entry_phys_t *vimep =
1830 &vim->vim_entries[i];
1831 (void) printf("\t<%llx:%llx:%llx> -> "
1832 "<%llx:%llx:%llx> (%x obsolete)\n",
1833 (longlong_t)vd->vdev_id,
1834 (longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
1835 (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1836 (longlong_t)DVA_GET_VDEV(&vimep->vimep_dst),
1837 (longlong_t)DVA_GET_OFFSET(&vimep->vimep_dst),
1838 (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1839 counts[i]);
1841 (void) printf("\n");
1843 uint64_t obsolete_sm_object;
1844 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
1845 if (obsolete_sm_object != 0) {
1846 objset_t *mos = vd->vdev_spa->spa_meta_objset;
1847 (void) printf("obsolete space map object %llu:\n",
1848 (u_longlong_t)obsolete_sm_object);
1849 ASSERT(vd->vdev_obsolete_sm != NULL);
1850 ASSERT3U(space_map_object(vd->vdev_obsolete_sm), ==,
1851 obsolete_sm_object);
1852 dump_spacemap(mos, vd->vdev_obsolete_sm);
1853 (void) printf("\n");
1857 static void
1858 dump_metaslabs(spa_t *spa)
1860 vdev_t *vd, *rvd = spa->spa_root_vdev;
1861 uint64_t m, c = 0, children = rvd->vdev_children;
1863 (void) printf("\nMetaslabs:\n");
1865 if (!dump_opt['d'] && zopt_metaslab_args > 0) {
1866 c = zopt_metaslab[0];
1868 if (c >= children)
1869 (void) fatal("bad vdev id: %llu", (u_longlong_t)c);
1871 if (zopt_metaslab_args > 1) {
1872 vd = rvd->vdev_child[c];
1873 print_vdev_metaslab_header(vd);
1875 for (m = 1; m < zopt_metaslab_args; m++) {
1876 if (zopt_metaslab[m] < vd->vdev_ms_count)
1877 dump_metaslab(
1878 vd->vdev_ms[zopt_metaslab[m]]);
1879 else
1880 (void) fprintf(stderr, "bad metaslab "
1881 "number %llu\n",
1882 (u_longlong_t)zopt_metaslab[m]);
1884 (void) printf("\n");
1885 return;
1887 children = c + 1;
1889 for (; c < children; c++) {
1890 vd = rvd->vdev_child[c];
1891 print_vdev_metaslab_header(vd);
1893 print_vdev_indirect(vd);
1895 for (m = 0; m < vd->vdev_ms_count; m++)
1896 dump_metaslab(vd->vdev_ms[m]);
1897 (void) printf("\n");
1901 static void
1902 dump_log_spacemaps(spa_t *spa)
1904 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
1905 return;
1907 (void) printf("\nLog Space Maps in Pool:\n");
1908 for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
1909 sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls)) {
1910 space_map_t *sm = NULL;
1911 VERIFY0(space_map_open(&sm, spa_meta_objset(spa),
1912 sls->sls_sm_obj, 0, UINT64_MAX, SPA_MINBLOCKSHIFT));
1914 (void) printf("Log Spacemap object %llu txg %llu\n",
1915 (u_longlong_t)sls->sls_sm_obj, (u_longlong_t)sls->sls_txg);
1916 dump_spacemap(spa->spa_meta_objset, sm);
1917 space_map_close(sm);
1919 (void) printf("\n");
1922 static void
1923 dump_ddt_entry(const ddt_t *ddt, const ddt_lightweight_entry_t *ddlwe,
1924 uint64_t index)
1926 const ddt_key_t *ddk = &ddlwe->ddlwe_key;
1927 char blkbuf[BP_SPRINTF_LEN];
1928 blkptr_t blk;
1929 int p;
1931 for (p = 0; p < DDT_NPHYS(ddt); p++) {
1932 const ddt_univ_phys_t *ddp = &ddlwe->ddlwe_phys;
1933 ddt_phys_variant_t v = DDT_PHYS_VARIANT(ddt, p);
1935 if (ddt_phys_birth(ddp, v) == 0)
1936 continue;
1937 ddt_bp_create(ddt->ddt_checksum, ddk, ddp, v, &blk);
1938 snprintf_blkptr(blkbuf, sizeof (blkbuf), &blk);
1939 (void) printf("index %llx refcnt %llu phys %d %s\n",
1940 (u_longlong_t)index, (u_longlong_t)ddt_phys_refcnt(ddp, v),
1941 p, blkbuf);
1945 static void
1946 dump_dedup_ratio(const ddt_stat_t *dds)
1948 double rL, rP, rD, D, dedup, compress, copies;
1950 if (dds->dds_blocks == 0)
1951 return;
1953 rL = (double)dds->dds_ref_lsize;
1954 rP = (double)dds->dds_ref_psize;
1955 rD = (double)dds->dds_ref_dsize;
1956 D = (double)dds->dds_dsize;
1958 dedup = rD / D;
1959 compress = rL / rP;
1960 copies = rD / rP;
1962 (void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
1963 "dedup * compress / copies = %.2f\n\n",
1964 dedup, compress, copies, dedup * compress / copies);
1967 static void
1968 dump_ddt_log(ddt_t *ddt)
1970 for (int n = 0; n < 2; n++) {
1971 ddt_log_t *ddl = &ddt->ddt_log[n];
1973 uint64_t count = avl_numnodes(&ddl->ddl_tree);
1974 if (count == 0)
1975 continue;
1977 printf(DMU_POOL_DDT_LOG ": %lu log entries\n",
1978 zio_checksum_table[ddt->ddt_checksum].ci_name, n, count);
1980 if (dump_opt['D'] < 4)
1981 continue;
1983 ddt_lightweight_entry_t ddlwe;
1984 uint64_t index = 0;
1985 for (ddt_log_entry_t *ddle = avl_first(&ddl->ddl_tree);
1986 ddle; ddle = AVL_NEXT(&ddl->ddl_tree, ddle)) {
1987 DDT_LOG_ENTRY_TO_LIGHTWEIGHT(ddt, ddle, &ddlwe);
1988 dump_ddt_entry(ddt, &ddlwe, index++);
1993 static void
1994 dump_ddt(ddt_t *ddt, ddt_type_t type, ddt_class_t class)
1996 char name[DDT_NAMELEN];
1997 ddt_lightweight_entry_t ddlwe;
1998 uint64_t walk = 0;
1999 dmu_object_info_t doi;
2000 uint64_t count, dspace, mspace;
2001 int error;
2003 error = ddt_object_info(ddt, type, class, &doi);
2005 if (error == ENOENT)
2006 return;
2007 ASSERT(error == 0);
2009 error = ddt_object_count(ddt, type, class, &count);
2010 ASSERT(error == 0);
2011 if (count == 0)
2012 return;
2014 dspace = doi.doi_physical_blocks_512 << 9;
2015 mspace = doi.doi_fill_count * doi.doi_data_block_size;
2017 ddt_object_name(ddt, type, class, name);
2019 (void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
2020 name,
2021 (u_longlong_t)count,
2022 (u_longlong_t)dspace,
2023 (u_longlong_t)mspace);
2025 if (dump_opt['D'] < 3)
2026 return;
2028 zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
2030 if (dump_opt['D'] < 4)
2031 return;
2033 if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
2034 return;
2036 (void) printf("%s contents:\n\n", name);
2038 while ((error = ddt_object_walk(ddt, type, class, &walk, &ddlwe)) == 0)
2039 dump_ddt_entry(ddt, &ddlwe, walk);
2041 ASSERT3U(error, ==, ENOENT);
2043 (void) printf("\n");
2046 static void
2047 dump_all_ddts(spa_t *spa)
2049 ddt_histogram_t ddh_total = {{{0}}};
2050 ddt_stat_t dds_total = {0};
2052 for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
2053 ddt_t *ddt = spa->spa_ddt[c];
2054 if (!ddt || ddt->ddt_version == DDT_VERSION_UNCONFIGURED)
2055 continue;
2056 for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
2057 for (ddt_class_t class = 0; class < DDT_CLASSES;
2058 class++) {
2059 dump_ddt(ddt, type, class);
2062 dump_ddt_log(ddt);
2065 ddt_get_dedup_stats(spa, &dds_total);
2067 if (dds_total.dds_blocks == 0) {
2068 (void) printf("All DDTs are empty\n");
2069 return;
2072 (void) printf("\n");
2074 if (dump_opt['D'] > 1) {
2075 (void) printf("DDT histogram (aggregated over all DDTs):\n");
2076 ddt_get_dedup_histogram(spa, &ddh_total);
2077 zpool_dump_ddt(&dds_total, &ddh_total);
2080 dump_dedup_ratio(&dds_total);
2083 * Dump a histogram of unique class entry age
2085 if (dump_opt['D'] == 3 && getenv("ZDB_DDT_UNIQUE_AGE_HIST") != NULL) {
2086 ddt_age_histo_t histogram;
2088 (void) printf("DDT walk unique, building age histogram...\n");
2089 ddt_prune_walk(spa, 0, &histogram);
2092 * print out histogram for unique entry class birth
2094 if (histogram.dah_entries > 0) {
2095 (void) printf("%5s %9s %4s\n",
2096 "age", "blocks", "amnt");
2097 (void) printf("%5s %9s %4s\n",
2098 "-----", "---------", "----");
2099 for (int i = 0; i < HIST_BINS; i++) {
2100 (void) printf("%5d %9d %4d%%\n", 1 << i,
2101 (int)histogram.dah_age_histo[i],
2102 (int)((histogram.dah_age_histo[i] * 100) /
2103 histogram.dah_entries));
2109 static void
2110 dump_brt(spa_t *spa)
2112 if (!spa_feature_is_enabled(spa, SPA_FEATURE_BLOCK_CLONING)) {
2113 printf("BRT: unsupported on this pool\n");
2114 return;
2117 if (!spa_feature_is_active(spa, SPA_FEATURE_BLOCK_CLONING)) {
2118 printf("BRT: empty\n");
2119 return;
2122 brt_t *brt = spa->spa_brt;
2123 VERIFY(brt);
2125 char count[32], used[32], saved[32];
2126 zdb_nicebytes(brt_get_used(spa), used, sizeof (used));
2127 zdb_nicebytes(brt_get_saved(spa), saved, sizeof (saved));
2128 uint64_t ratio = brt_get_ratio(spa);
2129 printf("BRT: used %s; saved %s; ratio %llu.%02llux\n", used, saved,
2130 (u_longlong_t)(ratio / 100), (u_longlong_t)(ratio % 100));
2132 if (dump_opt['T'] < 2)
2133 return;
2135 for (uint64_t vdevid = 0; vdevid < brt->brt_nvdevs; vdevid++) {
2136 brt_vdev_t *brtvd = &brt->brt_vdevs[vdevid];
2137 if (brtvd == NULL)
2138 continue;
2140 if (!brtvd->bv_initiated) {
2141 printf("BRT: vdev %" PRIu64 ": empty\n", vdevid);
2142 continue;
2145 zdb_nicenum(brtvd->bv_totalcount, count, sizeof (count));
2146 zdb_nicebytes(brtvd->bv_usedspace, used, sizeof (used));
2147 zdb_nicebytes(brtvd->bv_savedspace, saved, sizeof (saved));
2148 printf("BRT: vdev %" PRIu64 ": refcnt %s; used %s; saved %s\n",
2149 vdevid, count, used, saved);
2152 if (dump_opt['T'] < 3)
2153 return;
2155 /* -TTT shows a per-vdev histograms; -TTTT shows all entries */
2156 boolean_t do_histo = dump_opt['T'] == 3;
2158 char dva[64];
2160 if (!do_histo)
2161 printf("\n%-16s %-10s\n", "DVA", "REFCNT");
2163 for (uint64_t vdevid = 0; vdevid < brt->brt_nvdevs; vdevid++) {
2164 brt_vdev_t *brtvd = &brt->brt_vdevs[vdevid];
2165 if (brtvd == NULL || !brtvd->bv_initiated)
2166 continue;
2168 uint64_t counts[64] = {};
2170 zap_cursor_t zc;
2171 zap_attribute_t *za = zap_attribute_alloc();
2172 for (zap_cursor_init(&zc, brt->brt_mos, brtvd->bv_mos_entries);
2173 zap_cursor_retrieve(&zc, za) == 0;
2174 zap_cursor_advance(&zc)) {
2175 uint64_t refcnt;
2176 VERIFY0(zap_lookup_uint64(brt->brt_mos,
2177 brtvd->bv_mos_entries,
2178 (const uint64_t *)za->za_name, 1,
2179 za->za_integer_length, za->za_num_integers,
2180 &refcnt));
2182 if (do_histo)
2183 counts[highbit64(refcnt)]++;
2184 else {
2185 uint64_t offset =
2186 *(const uint64_t *)za->za_name;
2188 snprintf(dva, sizeof (dva), "%" PRIu64 ":%llx",
2189 vdevid, (u_longlong_t)offset);
2190 printf("%-16s %-10llu\n", dva,
2191 (u_longlong_t)refcnt);
2194 zap_cursor_fini(&zc);
2195 zap_attribute_free(za);
2197 if (do_histo) {
2198 printf("\nBRT: vdev %" PRIu64
2199 ": DVAs with 2^n refcnts:\n", vdevid);
2200 dump_histogram(counts, 64, 0);
2205 static void
2206 dump_dtl_seg(void *arg, uint64_t start, uint64_t size)
2208 char *prefix = arg;
2210 (void) printf("%s [%llu,%llu) length %llu\n",
2211 prefix,
2212 (u_longlong_t)start,
2213 (u_longlong_t)(start + size),
2214 (u_longlong_t)(size));
2217 static void
2218 dump_dtl(vdev_t *vd, int indent)
2220 spa_t *spa = vd->vdev_spa;
2221 boolean_t required;
2222 const char *name[DTL_TYPES] = { "missing", "partial", "scrub",
2223 "outage" };
2224 char prefix[256];
2226 spa_vdev_state_enter(spa, SCL_NONE);
2227 required = vdev_dtl_required(vd);
2228 (void) spa_vdev_state_exit(spa, NULL, 0);
2230 if (indent == 0)
2231 (void) printf("\nDirty time logs:\n\n");
2233 (void) printf("\t%*s%s [%s]\n", indent, "",
2234 vd->vdev_path ? vd->vdev_path :
2235 vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
2236 required ? "DTL-required" : "DTL-expendable");
2238 for (int t = 0; t < DTL_TYPES; t++) {
2239 range_tree_t *rt = vd->vdev_dtl[t];
2240 if (range_tree_space(rt) == 0)
2241 continue;
2242 (void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
2243 indent + 2, "", name[t]);
2244 range_tree_walk(rt, dump_dtl_seg, prefix);
2245 if (dump_opt['d'] > 5 && vd->vdev_children == 0)
2246 dump_spacemap(spa->spa_meta_objset,
2247 vd->vdev_dtl_sm);
2250 for (unsigned c = 0; c < vd->vdev_children; c++)
2251 dump_dtl(vd->vdev_child[c], indent + 4);
2254 static void
2255 dump_history(spa_t *spa)
2257 nvlist_t **events = NULL;
2258 char *buf;
2259 uint64_t resid, len, off = 0;
2260 uint_t num = 0;
2261 int error;
2262 char tbuf[30];
2264 if ((buf = malloc(SPA_OLD_MAXBLOCKSIZE)) == NULL) {
2265 (void) fprintf(stderr, "%s: unable to allocate I/O buffer\n",
2266 __func__);
2267 return;
2270 do {
2271 len = SPA_OLD_MAXBLOCKSIZE;
2273 if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
2274 (void) fprintf(stderr, "Unable to read history: "
2275 "error %d\n", error);
2276 free(buf);
2277 return;
2280 if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
2281 break;
2283 off -= resid;
2284 } while (len != 0);
2286 (void) printf("\nHistory:\n");
2287 for (unsigned i = 0; i < num; i++) {
2288 boolean_t printed = B_FALSE;
2290 if (nvlist_exists(events[i], ZPOOL_HIST_TIME)) {
2291 time_t tsec;
2292 struct tm t;
2294 tsec = fnvlist_lookup_uint64(events[i],
2295 ZPOOL_HIST_TIME);
2296 (void) localtime_r(&tsec, &t);
2297 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
2298 } else {
2299 tbuf[0] = '\0';
2302 if (nvlist_exists(events[i], ZPOOL_HIST_CMD)) {
2303 (void) printf("%s %s\n", tbuf,
2304 fnvlist_lookup_string(events[i], ZPOOL_HIST_CMD));
2305 } else if (nvlist_exists(events[i], ZPOOL_HIST_INT_EVENT)) {
2306 uint64_t ievent;
2308 ievent = fnvlist_lookup_uint64(events[i],
2309 ZPOOL_HIST_INT_EVENT);
2310 if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
2311 goto next;
2313 (void) printf(" %s [internal %s txg:%ju] %s\n",
2314 tbuf,
2315 zfs_history_event_names[ievent],
2316 fnvlist_lookup_uint64(events[i],
2317 ZPOOL_HIST_TXG),
2318 fnvlist_lookup_string(events[i],
2319 ZPOOL_HIST_INT_STR));
2320 } else if (nvlist_exists(events[i], ZPOOL_HIST_INT_NAME)) {
2321 (void) printf("%s [txg:%ju] %s", tbuf,
2322 fnvlist_lookup_uint64(events[i],
2323 ZPOOL_HIST_TXG),
2324 fnvlist_lookup_string(events[i],
2325 ZPOOL_HIST_INT_NAME));
2327 if (nvlist_exists(events[i], ZPOOL_HIST_DSNAME)) {
2328 (void) printf(" %s (%llu)",
2329 fnvlist_lookup_string(events[i],
2330 ZPOOL_HIST_DSNAME),
2331 (u_longlong_t)fnvlist_lookup_uint64(
2332 events[i],
2333 ZPOOL_HIST_DSID));
2336 (void) printf(" %s\n", fnvlist_lookup_string(events[i],
2337 ZPOOL_HIST_INT_STR));
2338 } else if (nvlist_exists(events[i], ZPOOL_HIST_IOCTL)) {
2339 (void) printf("%s ioctl %s\n", tbuf,
2340 fnvlist_lookup_string(events[i],
2341 ZPOOL_HIST_IOCTL));
2343 if (nvlist_exists(events[i], ZPOOL_HIST_INPUT_NVL)) {
2344 (void) printf(" input:\n");
2345 dump_nvlist(fnvlist_lookup_nvlist(events[i],
2346 ZPOOL_HIST_INPUT_NVL), 8);
2348 if (nvlist_exists(events[i], ZPOOL_HIST_OUTPUT_NVL)) {
2349 (void) printf(" output:\n");
2350 dump_nvlist(fnvlist_lookup_nvlist(events[i],
2351 ZPOOL_HIST_OUTPUT_NVL), 8);
2353 if (nvlist_exists(events[i], ZPOOL_HIST_ERRNO)) {
2354 (void) printf(" errno: %lld\n",
2355 (longlong_t)fnvlist_lookup_int64(events[i],
2356 ZPOOL_HIST_ERRNO));
2358 } else {
2359 goto next;
2362 printed = B_TRUE;
2363 next:
2364 if (dump_opt['h'] > 1) {
2365 if (!printed)
2366 (void) printf("unrecognized record:\n");
2367 dump_nvlist(events[i], 2);
2370 free(buf);
2373 static void
2374 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
2376 (void) os, (void) object, (void) data, (void) size;
2379 static uint64_t
2380 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp,
2381 const zbookmark_phys_t *zb)
2383 if (dnp == NULL) {
2384 ASSERT(zb->zb_level < 0);
2385 if (zb->zb_object == 0)
2386 return (zb->zb_blkid);
2387 return (zb->zb_blkid * BP_GET_LSIZE(bp));
2390 ASSERT(zb->zb_level >= 0);
2392 return ((zb->zb_blkid <<
2393 (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
2394 dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
2397 static void
2398 snprintf_zstd_header(spa_t *spa, char *blkbuf, size_t buflen,
2399 const blkptr_t *bp)
2401 static abd_t *pabd = NULL;
2402 void *buf;
2403 zio_t *zio;
2404 zfs_zstdhdr_t zstd_hdr;
2405 int error;
2407 if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_ZSTD)
2408 return;
2410 if (BP_IS_HOLE(bp))
2411 return;
2413 if (BP_IS_EMBEDDED(bp)) {
2414 buf = malloc(SPA_MAXBLOCKSIZE);
2415 if (buf == NULL) {
2416 (void) fprintf(stderr, "out of memory\n");
2417 zdb_exit(1);
2419 decode_embedded_bp_compressed(bp, buf);
2420 memcpy(&zstd_hdr, buf, sizeof (zstd_hdr));
2421 free(buf);
2422 zstd_hdr.c_len = BE_32(zstd_hdr.c_len);
2423 zstd_hdr.raw_version_level = BE_32(zstd_hdr.raw_version_level);
2424 (void) snprintf(blkbuf + strlen(blkbuf),
2425 buflen - strlen(blkbuf),
2426 " ZSTD:size=%u:version=%u:level=%u:EMBEDDED",
2427 zstd_hdr.c_len, zfs_get_hdrversion(&zstd_hdr),
2428 zfs_get_hdrlevel(&zstd_hdr));
2429 return;
2432 if (!pabd)
2433 pabd = abd_alloc_for_io(SPA_MAXBLOCKSIZE, B_FALSE);
2434 zio = zio_root(spa, NULL, NULL, 0);
2436 /* Decrypt but don't decompress so we can read the compression header */
2437 zio_nowait(zio_read(zio, spa, bp, pabd, BP_GET_PSIZE(bp), NULL, NULL,
2438 ZIO_PRIORITY_SYNC_READ, ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW_COMPRESS,
2439 NULL));
2440 error = zio_wait(zio);
2441 if (error) {
2442 (void) fprintf(stderr, "read failed: %d\n", error);
2443 return;
2445 buf = abd_borrow_buf_copy(pabd, BP_GET_LSIZE(bp));
2446 memcpy(&zstd_hdr, buf, sizeof (zstd_hdr));
2447 zstd_hdr.c_len = BE_32(zstd_hdr.c_len);
2448 zstd_hdr.raw_version_level = BE_32(zstd_hdr.raw_version_level);
2450 (void) snprintf(blkbuf + strlen(blkbuf),
2451 buflen - strlen(blkbuf),
2452 " ZSTD:size=%u:version=%u:level=%u:NORMAL",
2453 zstd_hdr.c_len, zfs_get_hdrversion(&zstd_hdr),
2454 zfs_get_hdrlevel(&zstd_hdr));
2456 abd_return_buf_copy(pabd, buf, BP_GET_LSIZE(bp));
2459 static void
2460 snprintf_blkptr_compact(char *blkbuf, size_t buflen, const blkptr_t *bp,
2461 boolean_t bp_freed)
2463 const dva_t *dva = bp->blk_dva;
2464 int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
2465 int i;
2467 if (dump_opt['b'] >= 6) {
2468 snprintf_blkptr(blkbuf, buflen, bp);
2469 if (bp_freed) {
2470 (void) snprintf(blkbuf + strlen(blkbuf),
2471 buflen - strlen(blkbuf), " %s", "FREE");
2473 return;
2476 if (BP_IS_EMBEDDED(bp)) {
2477 (void) sprintf(blkbuf,
2478 "EMBEDDED et=%u %llxL/%llxP B=%llu",
2479 (int)BPE_GET_ETYPE(bp),
2480 (u_longlong_t)BPE_GET_LSIZE(bp),
2481 (u_longlong_t)BPE_GET_PSIZE(bp),
2482 (u_longlong_t)BP_GET_LOGICAL_BIRTH(bp));
2483 return;
2486 blkbuf[0] = '\0';
2488 for (i = 0; i < ndvas; i++)
2489 (void) snprintf(blkbuf + strlen(blkbuf),
2490 buflen - strlen(blkbuf), "%llu:%llx:%llx ",
2491 (u_longlong_t)DVA_GET_VDEV(&dva[i]),
2492 (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
2493 (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
2495 if (BP_IS_HOLE(bp)) {
2496 (void) snprintf(blkbuf + strlen(blkbuf),
2497 buflen - strlen(blkbuf),
2498 "%llxL B=%llu",
2499 (u_longlong_t)BP_GET_LSIZE(bp),
2500 (u_longlong_t)BP_GET_LOGICAL_BIRTH(bp));
2501 } else {
2502 (void) snprintf(blkbuf + strlen(blkbuf),
2503 buflen - strlen(blkbuf),
2504 "%llxL/%llxP F=%llu B=%llu/%llu",
2505 (u_longlong_t)BP_GET_LSIZE(bp),
2506 (u_longlong_t)BP_GET_PSIZE(bp),
2507 (u_longlong_t)BP_GET_FILL(bp),
2508 (u_longlong_t)BP_GET_LOGICAL_BIRTH(bp),
2509 (u_longlong_t)BP_GET_BIRTH(bp));
2510 if (bp_freed)
2511 (void) snprintf(blkbuf + strlen(blkbuf),
2512 buflen - strlen(blkbuf), " %s", "FREE");
2513 (void) snprintf(blkbuf + strlen(blkbuf),
2514 buflen - strlen(blkbuf),
2515 " cksum=%016llx:%016llx:%016llx:%016llx",
2516 (u_longlong_t)bp->blk_cksum.zc_word[0],
2517 (u_longlong_t)bp->blk_cksum.zc_word[1],
2518 (u_longlong_t)bp->blk_cksum.zc_word[2],
2519 (u_longlong_t)bp->blk_cksum.zc_word[3]);
2523 static void
2524 print_indirect(spa_t *spa, blkptr_t *bp, const zbookmark_phys_t *zb,
2525 const dnode_phys_t *dnp)
2527 char blkbuf[BP_SPRINTF_LEN];
2528 int l;
2530 if (!BP_IS_EMBEDDED(bp)) {
2531 ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
2532 ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
2535 (void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
2537 ASSERT(zb->zb_level >= 0);
2539 for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
2540 if (l == zb->zb_level) {
2541 (void) printf("L%llx", (u_longlong_t)zb->zb_level);
2542 } else {
2543 (void) printf(" ");
2547 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp, B_FALSE);
2548 if (dump_opt['Z'] && BP_GET_COMPRESS(bp) == ZIO_COMPRESS_ZSTD)
2549 snprintf_zstd_header(spa, blkbuf, sizeof (blkbuf), bp);
2550 (void) printf("%s\n", blkbuf);
2553 static int
2554 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
2555 blkptr_t *bp, const zbookmark_phys_t *zb)
2557 int err = 0;
2559 if (BP_GET_LOGICAL_BIRTH(bp) == 0)
2560 return (0);
2562 print_indirect(spa, bp, zb, dnp);
2564 if (BP_GET_LEVEL(bp) > 0 && !BP_IS_HOLE(bp)) {
2565 arc_flags_t flags = ARC_FLAG_WAIT;
2566 int i;
2567 blkptr_t *cbp;
2568 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
2569 arc_buf_t *buf;
2570 uint64_t fill = 0;
2571 ASSERT(!BP_IS_REDACTED(bp));
2573 err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
2574 ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
2575 if (err)
2576 return (err);
2577 ASSERT(buf->b_data);
2579 /* recursively visit blocks below this */
2580 cbp = buf->b_data;
2581 for (i = 0; i < epb; i++, cbp++) {
2582 zbookmark_phys_t czb;
2584 SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
2585 zb->zb_level - 1,
2586 zb->zb_blkid * epb + i);
2587 err = visit_indirect(spa, dnp, cbp, &czb);
2588 if (err)
2589 break;
2590 fill += BP_GET_FILL(cbp);
2592 if (!err)
2593 ASSERT3U(fill, ==, BP_GET_FILL(bp));
2594 arc_buf_destroy(buf, &buf);
2597 return (err);
2600 static void
2601 dump_indirect(dnode_t *dn)
2603 dnode_phys_t *dnp = dn->dn_phys;
2604 zbookmark_phys_t czb;
2606 (void) printf("Indirect blocks:\n");
2608 SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
2609 dn->dn_object, dnp->dn_nlevels - 1, 0);
2610 for (int j = 0; j < dnp->dn_nblkptr; j++) {
2611 czb.zb_blkid = j;
2612 (void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
2613 &dnp->dn_blkptr[j], &czb);
2616 (void) printf("\n");
2619 static void
2620 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
2622 (void) os, (void) object;
2623 dsl_dir_phys_t *dd = data;
2624 time_t crtime;
2625 char nice[32];
2627 /* make sure nicenum has enough space */
2628 _Static_assert(sizeof (nice) >= NN_NUMBUF_SZ, "nice truncated");
2630 if (dd == NULL)
2631 return;
2633 ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
2635 crtime = dd->dd_creation_time;
2636 (void) printf("\t\tcreation_time = %s", ctime(&crtime));
2637 (void) printf("\t\thead_dataset_obj = %llu\n",
2638 (u_longlong_t)dd->dd_head_dataset_obj);
2639 (void) printf("\t\tparent_dir_obj = %llu\n",
2640 (u_longlong_t)dd->dd_parent_obj);
2641 (void) printf("\t\torigin_obj = %llu\n",
2642 (u_longlong_t)dd->dd_origin_obj);
2643 (void) printf("\t\tchild_dir_zapobj = %llu\n",
2644 (u_longlong_t)dd->dd_child_dir_zapobj);
2645 zdb_nicenum(dd->dd_used_bytes, nice, sizeof (nice));
2646 (void) printf("\t\tused_bytes = %s\n", nice);
2647 zdb_nicenum(dd->dd_compressed_bytes, nice, sizeof (nice));
2648 (void) printf("\t\tcompressed_bytes = %s\n", nice);
2649 zdb_nicenum(dd->dd_uncompressed_bytes, nice, sizeof (nice));
2650 (void) printf("\t\tuncompressed_bytes = %s\n", nice);
2651 zdb_nicenum(dd->dd_quota, nice, sizeof (nice));
2652 (void) printf("\t\tquota = %s\n", nice);
2653 zdb_nicenum(dd->dd_reserved, nice, sizeof (nice));
2654 (void) printf("\t\treserved = %s\n", nice);
2655 (void) printf("\t\tprops_zapobj = %llu\n",
2656 (u_longlong_t)dd->dd_props_zapobj);
2657 (void) printf("\t\tdeleg_zapobj = %llu\n",
2658 (u_longlong_t)dd->dd_deleg_zapobj);
2659 (void) printf("\t\tflags = %llx\n",
2660 (u_longlong_t)dd->dd_flags);
2662 #define DO(which) \
2663 zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice, \
2664 sizeof (nice)); \
2665 (void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
2666 DO(HEAD);
2667 DO(SNAP);
2668 DO(CHILD);
2669 DO(CHILD_RSRV);
2670 DO(REFRSRV);
2671 #undef DO
2672 (void) printf("\t\tclones = %llu\n",
2673 (u_longlong_t)dd->dd_clones);
2676 static void
2677 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
2679 (void) os, (void) object;
2680 dsl_dataset_phys_t *ds = data;
2681 time_t crtime;
2682 char used[32], compressed[32], uncompressed[32], unique[32];
2683 char blkbuf[BP_SPRINTF_LEN];
2685 /* make sure nicenum has enough space */
2686 _Static_assert(sizeof (used) >= NN_NUMBUF_SZ, "used truncated");
2687 _Static_assert(sizeof (compressed) >= NN_NUMBUF_SZ,
2688 "compressed truncated");
2689 _Static_assert(sizeof (uncompressed) >= NN_NUMBUF_SZ,
2690 "uncompressed truncated");
2691 _Static_assert(sizeof (unique) >= NN_NUMBUF_SZ, "unique truncated");
2693 if (ds == NULL)
2694 return;
2696 ASSERT(size == sizeof (*ds));
2697 crtime = ds->ds_creation_time;
2698 zdb_nicenum(ds->ds_referenced_bytes, used, sizeof (used));
2699 zdb_nicenum(ds->ds_compressed_bytes, compressed, sizeof (compressed));
2700 zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed,
2701 sizeof (uncompressed));
2702 zdb_nicenum(ds->ds_unique_bytes, unique, sizeof (unique));
2703 snprintf_blkptr(blkbuf, sizeof (blkbuf), &ds->ds_bp);
2705 (void) printf("\t\tdir_obj = %llu\n",
2706 (u_longlong_t)ds->ds_dir_obj);
2707 (void) printf("\t\tprev_snap_obj = %llu\n",
2708 (u_longlong_t)ds->ds_prev_snap_obj);
2709 (void) printf("\t\tprev_snap_txg = %llu\n",
2710 (u_longlong_t)ds->ds_prev_snap_txg);
2711 (void) printf("\t\tnext_snap_obj = %llu\n",
2712 (u_longlong_t)ds->ds_next_snap_obj);
2713 (void) printf("\t\tsnapnames_zapobj = %llu\n",
2714 (u_longlong_t)ds->ds_snapnames_zapobj);
2715 (void) printf("\t\tnum_children = %llu\n",
2716 (u_longlong_t)ds->ds_num_children);
2717 (void) printf("\t\tuserrefs_obj = %llu\n",
2718 (u_longlong_t)ds->ds_userrefs_obj);
2719 (void) printf("\t\tcreation_time = %s", ctime(&crtime));
2720 (void) printf("\t\tcreation_txg = %llu\n",
2721 (u_longlong_t)ds->ds_creation_txg);
2722 (void) printf("\t\tdeadlist_obj = %llu\n",
2723 (u_longlong_t)ds->ds_deadlist_obj);
2724 (void) printf("\t\tused_bytes = %s\n", used);
2725 (void) printf("\t\tcompressed_bytes = %s\n", compressed);
2726 (void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
2727 (void) printf("\t\tunique = %s\n", unique);
2728 (void) printf("\t\tfsid_guid = %llu\n",
2729 (u_longlong_t)ds->ds_fsid_guid);
2730 (void) printf("\t\tguid = %llu\n",
2731 (u_longlong_t)ds->ds_guid);
2732 (void) printf("\t\tflags = %llx\n",
2733 (u_longlong_t)ds->ds_flags);
2734 (void) printf("\t\tnext_clones_obj = %llu\n",
2735 (u_longlong_t)ds->ds_next_clones_obj);
2736 (void) printf("\t\tprops_obj = %llu\n",
2737 (u_longlong_t)ds->ds_props_obj);
2738 (void) printf("\t\tbp = %s\n", blkbuf);
2741 static int
2742 dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2744 (void) arg, (void) tx;
2745 char blkbuf[BP_SPRINTF_LEN];
2747 if (BP_GET_LOGICAL_BIRTH(bp) != 0) {
2748 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
2749 (void) printf("\t%s\n", blkbuf);
2751 return (0);
2754 static void
2755 dump_bptree(objset_t *os, uint64_t obj, const char *name)
2757 char bytes[32];
2758 bptree_phys_t *bt;
2759 dmu_buf_t *db;
2761 /* make sure nicenum has enough space */
2762 _Static_assert(sizeof (bytes) >= NN_NUMBUF_SZ, "bytes truncated");
2764 if (dump_opt['d'] < 3)
2765 return;
2767 VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
2768 bt = db->db_data;
2769 zdb_nicenum(bt->bt_bytes, bytes, sizeof (bytes));
2770 (void) printf("\n %s: %llu datasets, %s\n",
2771 name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
2772 dmu_buf_rele(db, FTAG);
2774 if (dump_opt['d'] < 5)
2775 return;
2777 (void) printf("\n");
2779 (void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
2782 static int
2783 dump_bpobj_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed, dmu_tx_t *tx)
2785 (void) arg, (void) tx;
2786 char blkbuf[BP_SPRINTF_LEN];
2788 ASSERT(BP_GET_LOGICAL_BIRTH(bp) != 0);
2789 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp, bp_freed);
2790 (void) printf("\t%s\n", blkbuf);
2791 return (0);
2794 static void
2795 dump_full_bpobj(bpobj_t *bpo, const char *name, int indent)
2797 char bytes[32];
2798 char comp[32];
2799 char uncomp[32];
2800 uint64_t i;
2802 /* make sure nicenum has enough space */
2803 _Static_assert(sizeof (bytes) >= NN_NUMBUF_SZ, "bytes truncated");
2804 _Static_assert(sizeof (comp) >= NN_NUMBUF_SZ, "comp truncated");
2805 _Static_assert(sizeof (uncomp) >= NN_NUMBUF_SZ, "uncomp truncated");
2807 if (dump_opt['d'] < 3)
2808 return;
2810 zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes, sizeof (bytes));
2811 if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
2812 zdb_nicenum(bpo->bpo_phys->bpo_comp, comp, sizeof (comp));
2813 zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp, sizeof (uncomp));
2814 if (bpo->bpo_havefreed) {
2815 (void) printf(" %*s: object %llu, %llu local "
2816 "blkptrs, %llu freed, %llu subobjs in object %llu, "
2817 "%s (%s/%s comp)\n",
2818 indent * 8, name,
2819 (u_longlong_t)bpo->bpo_object,
2820 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2821 (u_longlong_t)bpo->bpo_phys->bpo_num_freed,
2822 (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
2823 (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
2824 bytes, comp, uncomp);
2825 } else {
2826 (void) printf(" %*s: object %llu, %llu local "
2827 "blkptrs, %llu subobjs in object %llu, "
2828 "%s (%s/%s comp)\n",
2829 indent * 8, name,
2830 (u_longlong_t)bpo->bpo_object,
2831 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2832 (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
2833 (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
2834 bytes, comp, uncomp);
2837 for (i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
2838 uint64_t subobj;
2839 bpobj_t subbpo;
2840 int error;
2841 VERIFY0(dmu_read(bpo->bpo_os,
2842 bpo->bpo_phys->bpo_subobjs,
2843 i * sizeof (subobj), sizeof (subobj), &subobj, 0));
2844 error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
2845 if (error != 0) {
2846 (void) printf("ERROR %u while trying to open "
2847 "subobj id %llu\n",
2848 error, (u_longlong_t)subobj);
2849 continue;
2851 dump_full_bpobj(&subbpo, "subobj", indent + 1);
2852 bpobj_close(&subbpo);
2854 } else {
2855 if (bpo->bpo_havefreed) {
2856 (void) printf(" %*s: object %llu, %llu blkptrs, "
2857 "%llu freed, %s\n",
2858 indent * 8, name,
2859 (u_longlong_t)bpo->bpo_object,
2860 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2861 (u_longlong_t)bpo->bpo_phys->bpo_num_freed,
2862 bytes);
2863 } else {
2864 (void) printf(" %*s: object %llu, %llu blkptrs, "
2865 "%s\n",
2866 indent * 8, name,
2867 (u_longlong_t)bpo->bpo_object,
2868 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2869 bytes);
2873 if (dump_opt['d'] < 5)
2874 return;
2877 if (indent == 0) {
2878 (void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
2879 (void) printf("\n");
2883 static int
2884 dump_bookmark(dsl_pool_t *dp, char *name, boolean_t print_redact,
2885 boolean_t print_list)
2887 int err = 0;
2888 zfs_bookmark_phys_t prop;
2889 objset_t *mos = dp->dp_spa->spa_meta_objset;
2890 err = dsl_bookmark_lookup(dp, name, NULL, &prop);
2892 if (err != 0) {
2893 return (err);
2896 (void) printf("\t#%s: ", strchr(name, '#') + 1);
2897 (void) printf("{guid: %llx creation_txg: %llu creation_time: "
2898 "%llu redaction_obj: %llu}\n", (u_longlong_t)prop.zbm_guid,
2899 (u_longlong_t)prop.zbm_creation_txg,
2900 (u_longlong_t)prop.zbm_creation_time,
2901 (u_longlong_t)prop.zbm_redaction_obj);
2903 IMPLY(print_list, print_redact);
2904 if (!print_redact || prop.zbm_redaction_obj == 0)
2905 return (0);
2907 redaction_list_t *rl;
2908 VERIFY0(dsl_redaction_list_hold_obj(dp,
2909 prop.zbm_redaction_obj, FTAG, &rl));
2911 redaction_list_phys_t *rlp = rl->rl_phys;
2912 (void) printf("\tRedacted:\n\t\tProgress: ");
2913 if (rlp->rlp_last_object != UINT64_MAX ||
2914 rlp->rlp_last_blkid != UINT64_MAX) {
2915 (void) printf("%llu %llu (incomplete)\n",
2916 (u_longlong_t)rlp->rlp_last_object,
2917 (u_longlong_t)rlp->rlp_last_blkid);
2918 } else {
2919 (void) printf("complete\n");
2921 (void) printf("\t\tSnapshots: [");
2922 for (unsigned int i = 0; i < rlp->rlp_num_snaps; i++) {
2923 if (i > 0)
2924 (void) printf(", ");
2925 (void) printf("%0llu",
2926 (u_longlong_t)rlp->rlp_snaps[i]);
2928 (void) printf("]\n\t\tLength: %llu\n",
2929 (u_longlong_t)rlp->rlp_num_entries);
2931 if (!print_list) {
2932 dsl_redaction_list_rele(rl, FTAG);
2933 return (0);
2936 if (rlp->rlp_num_entries == 0) {
2937 dsl_redaction_list_rele(rl, FTAG);
2938 (void) printf("\t\tRedaction List: []\n\n");
2939 return (0);
2942 redact_block_phys_t *rbp_buf;
2943 uint64_t size;
2944 dmu_object_info_t doi;
2946 VERIFY0(dmu_object_info(mos, prop.zbm_redaction_obj, &doi));
2947 size = doi.doi_max_offset;
2948 rbp_buf = kmem_alloc(size, KM_SLEEP);
2950 err = dmu_read(mos, prop.zbm_redaction_obj, 0, size,
2951 rbp_buf, 0);
2952 if (err != 0) {
2953 dsl_redaction_list_rele(rl, FTAG);
2954 kmem_free(rbp_buf, size);
2955 return (err);
2958 (void) printf("\t\tRedaction List: [{object: %llx, offset: "
2959 "%llx, blksz: %x, count: %llx}",
2960 (u_longlong_t)rbp_buf[0].rbp_object,
2961 (u_longlong_t)rbp_buf[0].rbp_blkid,
2962 (uint_t)(redact_block_get_size(&rbp_buf[0])),
2963 (u_longlong_t)redact_block_get_count(&rbp_buf[0]));
2965 for (size_t i = 1; i < rlp->rlp_num_entries; i++) {
2966 (void) printf(",\n\t\t{object: %llx, offset: %llx, "
2967 "blksz: %x, count: %llx}",
2968 (u_longlong_t)rbp_buf[i].rbp_object,
2969 (u_longlong_t)rbp_buf[i].rbp_blkid,
2970 (uint_t)(redact_block_get_size(&rbp_buf[i])),
2971 (u_longlong_t)redact_block_get_count(&rbp_buf[i]));
2973 dsl_redaction_list_rele(rl, FTAG);
2974 kmem_free(rbp_buf, size);
2975 (void) printf("]\n\n");
2976 return (0);
2979 static void
2980 dump_bookmarks(objset_t *os, int verbosity)
2982 zap_cursor_t zc;
2983 zap_attribute_t *attrp;
2984 dsl_dataset_t *ds = dmu_objset_ds(os);
2985 dsl_pool_t *dp = spa_get_dsl(os->os_spa);
2986 objset_t *mos = os->os_spa->spa_meta_objset;
2987 if (verbosity < 4)
2988 return;
2989 attrp = zap_attribute_alloc();
2990 dsl_pool_config_enter(dp, FTAG);
2992 for (zap_cursor_init(&zc, mos, ds->ds_bookmarks_obj);
2993 zap_cursor_retrieve(&zc, attrp) == 0;
2994 zap_cursor_advance(&zc)) {
2995 char osname[ZFS_MAX_DATASET_NAME_LEN];
2996 char buf[ZFS_MAX_DATASET_NAME_LEN];
2997 int len;
2998 dmu_objset_name(os, osname);
2999 len = snprintf(buf, sizeof (buf), "%s#%s", osname,
3000 attrp->za_name);
3001 VERIFY3S(len, <, ZFS_MAX_DATASET_NAME_LEN);
3002 (void) dump_bookmark(dp, buf, verbosity >= 5, verbosity >= 6);
3004 zap_cursor_fini(&zc);
3005 dsl_pool_config_exit(dp, FTAG);
3006 zap_attribute_free(attrp);
3009 static void
3010 bpobj_count_refd(bpobj_t *bpo)
3012 mos_obj_refd(bpo->bpo_object);
3014 if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
3015 mos_obj_refd(bpo->bpo_phys->bpo_subobjs);
3016 for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
3017 uint64_t subobj;
3018 bpobj_t subbpo;
3019 int error;
3020 VERIFY0(dmu_read(bpo->bpo_os,
3021 bpo->bpo_phys->bpo_subobjs,
3022 i * sizeof (subobj), sizeof (subobj), &subobj, 0));
3023 error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
3024 if (error != 0) {
3025 (void) printf("ERROR %u while trying to open "
3026 "subobj id %llu\n",
3027 error, (u_longlong_t)subobj);
3028 continue;
3030 bpobj_count_refd(&subbpo);
3031 bpobj_close(&subbpo);
3036 static int
3037 dsl_deadlist_entry_count_refd(void *arg, dsl_deadlist_entry_t *dle)
3039 spa_t *spa = arg;
3040 uint64_t empty_bpobj = spa->spa_dsl_pool->dp_empty_bpobj;
3041 if (dle->dle_bpobj.bpo_object != empty_bpobj)
3042 bpobj_count_refd(&dle->dle_bpobj);
3043 return (0);
3046 static int
3047 dsl_deadlist_entry_dump(void *arg, dsl_deadlist_entry_t *dle)
3049 ASSERT(arg == NULL);
3050 if (dump_opt['d'] >= 5) {
3051 char buf[128];
3052 (void) snprintf(buf, sizeof (buf),
3053 "mintxg %llu -> obj %llu",
3054 (longlong_t)dle->dle_mintxg,
3055 (longlong_t)dle->dle_bpobj.bpo_object);
3057 dump_full_bpobj(&dle->dle_bpobj, buf, 0);
3058 } else {
3059 (void) printf("mintxg %llu -> obj %llu\n",
3060 (longlong_t)dle->dle_mintxg,
3061 (longlong_t)dle->dle_bpobj.bpo_object);
3063 return (0);
3066 static void
3067 dump_blkptr_list(dsl_deadlist_t *dl, const char *name)
3069 char bytes[32];
3070 char comp[32];
3071 char uncomp[32];
3072 char entries[32];
3073 spa_t *spa = dmu_objset_spa(dl->dl_os);
3074 uint64_t empty_bpobj = spa->spa_dsl_pool->dp_empty_bpobj;
3076 if (dl->dl_oldfmt) {
3077 if (dl->dl_bpobj.bpo_object != empty_bpobj)
3078 bpobj_count_refd(&dl->dl_bpobj);
3079 } else {
3080 mos_obj_refd(dl->dl_object);
3081 dsl_deadlist_iterate(dl, dsl_deadlist_entry_count_refd, spa);
3084 /* make sure nicenum has enough space */
3085 _Static_assert(sizeof (bytes) >= NN_NUMBUF_SZ, "bytes truncated");
3086 _Static_assert(sizeof (comp) >= NN_NUMBUF_SZ, "comp truncated");
3087 _Static_assert(sizeof (uncomp) >= NN_NUMBUF_SZ, "uncomp truncated");
3088 _Static_assert(sizeof (entries) >= NN_NUMBUF_SZ, "entries truncated");
3090 if (dump_opt['d'] < 3)
3091 return;
3093 if (dl->dl_oldfmt) {
3094 dump_full_bpobj(&dl->dl_bpobj, "old-format deadlist", 0);
3095 return;
3098 zdb_nicenum(dl->dl_phys->dl_used, bytes, sizeof (bytes));
3099 zdb_nicenum(dl->dl_phys->dl_comp, comp, sizeof (comp));
3100 zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp, sizeof (uncomp));
3101 zdb_nicenum(avl_numnodes(&dl->dl_tree), entries, sizeof (entries));
3102 (void) printf("\n %s: %s (%s/%s comp), %s entries\n",
3103 name, bytes, comp, uncomp, entries);
3105 if (dump_opt['d'] < 4)
3106 return;
3108 (void) putchar('\n');
3110 dsl_deadlist_iterate(dl, dsl_deadlist_entry_dump, NULL);
3113 static int
3114 verify_dd_livelist(objset_t *os)
3116 uint64_t ll_used, used, ll_comp, comp, ll_uncomp, uncomp;
3117 dsl_pool_t *dp = spa_get_dsl(os->os_spa);
3118 dsl_dir_t *dd = os->os_dsl_dataset->ds_dir;
3120 ASSERT(!dmu_objset_is_snapshot(os));
3121 if (!dsl_deadlist_is_open(&dd->dd_livelist))
3122 return (0);
3124 /* Iterate through the livelist to check for duplicates */
3125 dsl_deadlist_iterate(&dd->dd_livelist, sublivelist_verify_lightweight,
3126 NULL);
3128 dsl_pool_config_enter(dp, FTAG);
3129 dsl_deadlist_space(&dd->dd_livelist, &ll_used,
3130 &ll_comp, &ll_uncomp);
3132 dsl_dataset_t *origin_ds;
3133 ASSERT(dsl_pool_config_held(dp));
3134 VERIFY0(dsl_dataset_hold_obj(dp,
3135 dsl_dir_phys(dd)->dd_origin_obj, FTAG, &origin_ds));
3136 VERIFY0(dsl_dataset_space_written(origin_ds, os->os_dsl_dataset,
3137 &used, &comp, &uncomp));
3138 dsl_dataset_rele(origin_ds, FTAG);
3139 dsl_pool_config_exit(dp, FTAG);
3141 * It's possible that the dataset's uncomp space is larger than the
3142 * livelist's because livelists do not track embedded block pointers
3144 if (used != ll_used || comp != ll_comp || uncomp < ll_uncomp) {
3145 char nice_used[32], nice_comp[32], nice_uncomp[32];
3146 (void) printf("Discrepancy in space accounting:\n");
3147 zdb_nicenum(used, nice_used, sizeof (nice_used));
3148 zdb_nicenum(comp, nice_comp, sizeof (nice_comp));
3149 zdb_nicenum(uncomp, nice_uncomp, sizeof (nice_uncomp));
3150 (void) printf("dir: used %s, comp %s, uncomp %s\n",
3151 nice_used, nice_comp, nice_uncomp);
3152 zdb_nicenum(ll_used, nice_used, sizeof (nice_used));
3153 zdb_nicenum(ll_comp, nice_comp, sizeof (nice_comp));
3154 zdb_nicenum(ll_uncomp, nice_uncomp, sizeof (nice_uncomp));
3155 (void) printf("livelist: used %s, comp %s, uncomp %s\n",
3156 nice_used, nice_comp, nice_uncomp);
3157 return (1);
3159 return (0);
3162 static char *key_material = NULL;
3164 static boolean_t
3165 zdb_derive_key(dsl_dir_t *dd, uint8_t *key_out)
3167 uint64_t keyformat, salt, iters;
3168 int i;
3169 unsigned char c;
3171 VERIFY0(zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
3172 zfs_prop_to_name(ZFS_PROP_KEYFORMAT), sizeof (uint64_t),
3173 1, &keyformat));
3175 switch (keyformat) {
3176 case ZFS_KEYFORMAT_HEX:
3177 for (i = 0; i < WRAPPING_KEY_LEN * 2; i += 2) {
3178 if (!isxdigit(key_material[i]) ||
3179 !isxdigit(key_material[i+1]))
3180 return (B_FALSE);
3181 if (sscanf(&key_material[i], "%02hhx", &c) != 1)
3182 return (B_FALSE);
3183 key_out[i / 2] = c;
3185 break;
3187 case ZFS_KEYFORMAT_PASSPHRASE:
3188 VERIFY0(zap_lookup(dd->dd_pool->dp_meta_objset,
3189 dd->dd_crypto_obj, zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT),
3190 sizeof (uint64_t), 1, &salt));
3191 VERIFY0(zap_lookup(dd->dd_pool->dp_meta_objset,
3192 dd->dd_crypto_obj, zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS),
3193 sizeof (uint64_t), 1, &iters));
3195 if (PKCS5_PBKDF2_HMAC_SHA1(key_material, strlen(key_material),
3196 ((uint8_t *)&salt), sizeof (uint64_t), iters,
3197 WRAPPING_KEY_LEN, key_out) != 1)
3198 return (B_FALSE);
3200 break;
3202 default:
3203 fatal("no support for key format %u\n",
3204 (unsigned int) keyformat);
3207 return (B_TRUE);
3210 static char encroot[ZFS_MAX_DATASET_NAME_LEN];
3211 static boolean_t key_loaded = B_FALSE;
3213 static void
3214 zdb_load_key(objset_t *os)
3216 dsl_pool_t *dp;
3217 dsl_dir_t *dd, *rdd;
3218 uint8_t key[WRAPPING_KEY_LEN];
3219 uint64_t rddobj;
3220 int err;
3222 dp = spa_get_dsl(os->os_spa);
3223 dd = os->os_dsl_dataset->ds_dir;
3225 dsl_pool_config_enter(dp, FTAG);
3226 VERIFY0(zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
3227 DSL_CRYPTO_KEY_ROOT_DDOBJ, sizeof (uint64_t), 1, &rddobj));
3228 VERIFY0(dsl_dir_hold_obj(dd->dd_pool, rddobj, NULL, FTAG, &rdd));
3229 dsl_dir_name(rdd, encroot);
3230 dsl_dir_rele(rdd, FTAG);
3232 if (!zdb_derive_key(dd, key))
3233 fatal("couldn't derive encryption key");
3235 dsl_pool_config_exit(dp, FTAG);
3237 ASSERT3U(dsl_dataset_get_keystatus(dd), ==, ZFS_KEYSTATUS_UNAVAILABLE);
3239 dsl_crypto_params_t *dcp;
3240 nvlist_t *crypto_args;
3242 crypto_args = fnvlist_alloc();
3243 fnvlist_add_uint8_array(crypto_args, "wkeydata",
3244 (uint8_t *)key, WRAPPING_KEY_LEN);
3245 VERIFY0(dsl_crypto_params_create_nvlist(DCP_CMD_NONE,
3246 NULL, crypto_args, &dcp));
3247 err = spa_keystore_load_wkey(encroot, dcp, B_FALSE);
3249 dsl_crypto_params_free(dcp, (err != 0));
3250 fnvlist_free(crypto_args);
3252 if (err != 0)
3253 fatal(
3254 "couldn't load encryption key for %s: %s",
3255 encroot, err == ZFS_ERR_CRYPTO_NOTSUP ?
3256 "crypto params not supported" : strerror(err));
3258 ASSERT3U(dsl_dataset_get_keystatus(dd), ==, ZFS_KEYSTATUS_AVAILABLE);
3260 printf("Unlocked encryption root: %s\n", encroot);
3261 key_loaded = B_TRUE;
3264 static void
3265 zdb_unload_key(void)
3267 if (!key_loaded)
3268 return;
3270 VERIFY0(spa_keystore_unload_wkey(encroot));
3271 key_loaded = B_FALSE;
3274 static avl_tree_t idx_tree;
3275 static avl_tree_t domain_tree;
3276 static boolean_t fuid_table_loaded;
3277 static objset_t *sa_os = NULL;
3278 static sa_attr_type_t *sa_attr_table = NULL;
3280 static int
3281 open_objset(const char *path, const void *tag, objset_t **osp)
3283 int err;
3284 uint64_t sa_attrs = 0;
3285 uint64_t version = 0;
3287 VERIFY3P(sa_os, ==, NULL);
3290 * We can't own an objset if it's redacted. Therefore, we do this
3291 * dance: hold the objset, then acquire a long hold on its dataset, then
3292 * release the pool (which is held as part of holding the objset).
3295 if (dump_opt['K']) {
3296 /* decryption requested, try to load keys */
3297 err = dmu_objset_hold(path, tag, osp);
3298 if (err != 0) {
3299 (void) fprintf(stderr, "failed to hold dataset "
3300 "'%s': %s\n",
3301 path, strerror(err));
3302 return (err);
3304 dsl_dataset_long_hold(dmu_objset_ds(*osp), tag);
3305 dsl_pool_rele(dmu_objset_pool(*osp), tag);
3307 /* succeeds or dies */
3308 zdb_load_key(*osp);
3310 /* release it all */
3311 dsl_dataset_long_rele(dmu_objset_ds(*osp), tag);
3312 dsl_dataset_rele(dmu_objset_ds(*osp), tag);
3315 int ds_hold_flags = key_loaded ? DS_HOLD_FLAG_DECRYPT : 0;
3317 err = dmu_objset_hold_flags(path, ds_hold_flags, tag, osp);
3318 if (err != 0) {
3319 (void) fprintf(stderr, "failed to hold dataset '%s': %s\n",
3320 path, strerror(err));
3321 return (err);
3323 dsl_dataset_long_hold(dmu_objset_ds(*osp), tag);
3324 dsl_pool_rele(dmu_objset_pool(*osp), tag);
3326 if (dmu_objset_type(*osp) == DMU_OST_ZFS &&
3327 (key_loaded || !(*osp)->os_encrypted)) {
3328 (void) zap_lookup(*osp, MASTER_NODE_OBJ, ZPL_VERSION_STR,
3329 8, 1, &version);
3330 if (version >= ZPL_VERSION_SA) {
3331 (void) zap_lookup(*osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
3332 8, 1, &sa_attrs);
3334 err = sa_setup(*osp, sa_attrs, zfs_attr_table, ZPL_END,
3335 &sa_attr_table);
3336 if (err != 0) {
3337 (void) fprintf(stderr, "sa_setup failed: %s\n",
3338 strerror(err));
3339 dsl_dataset_long_rele(dmu_objset_ds(*osp), tag);
3340 dsl_dataset_rele_flags(dmu_objset_ds(*osp),
3341 ds_hold_flags, tag);
3342 *osp = NULL;
3345 sa_os = *osp;
3347 return (err);
3350 static void
3351 close_objset(objset_t *os, const void *tag)
3353 VERIFY3P(os, ==, sa_os);
3354 if (os->os_sa != NULL)
3355 sa_tear_down(os);
3356 dsl_dataset_long_rele(dmu_objset_ds(os), tag);
3357 dsl_dataset_rele_flags(dmu_objset_ds(os),
3358 key_loaded ? DS_HOLD_FLAG_DECRYPT : 0, tag);
3359 sa_attr_table = NULL;
3360 sa_os = NULL;
3362 zdb_unload_key();
3365 static void
3366 fuid_table_destroy(void)
3368 if (fuid_table_loaded) {
3369 zfs_fuid_table_destroy(&idx_tree, &domain_tree);
3370 fuid_table_loaded = B_FALSE;
3375 * Clean up DDT internal state. ddt_lookup() adds entries to ddt_tree, which on
3376 * a live pool are normally cleaned up during ddt_sync(). We can't do that (and
3377 * wouldn't want to anyway), but if we don't clean up the presence of stuff on
3378 * ddt_tree will trip asserts in ddt_table_free(). So, we clean up ourselves.
3380 * Note that this is not a particularly efficient way to do this, but
3381 * ddt_remove() is the only public method that can do the work we need, and it
3382 * requires the right locks and etc to do the job. This is only ever called
3383 * during zdb shutdown so efficiency is not especially important.
3385 static void
3386 zdb_ddt_cleanup(spa_t *spa)
3388 for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
3389 ddt_t *ddt = spa->spa_ddt[c];
3390 if (!ddt)
3391 continue;
3393 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3394 ddt_enter(ddt);
3395 ddt_entry_t *dde = avl_first(&ddt->ddt_tree), *next;
3396 while (dde) {
3397 next = AVL_NEXT(&ddt->ddt_tree, dde);
3398 dde->dde_io = NULL;
3399 ddt_remove(ddt, dde);
3400 dde = next;
3402 ddt_exit(ddt);
3403 spa_config_exit(spa, SCL_CONFIG, FTAG);
3407 static void
3408 zdb_exit(int reason)
3410 if (spa != NULL)
3411 zdb_ddt_cleanup(spa);
3413 if (os != NULL) {
3414 close_objset(os, FTAG);
3415 } else if (spa != NULL) {
3416 spa_close(spa, FTAG);
3419 fuid_table_destroy();
3421 if (kernel_init_done)
3422 kernel_fini();
3424 exit(reason);
3428 * print uid or gid information.
3429 * For normal POSIX id just the id is printed in decimal format.
3430 * For CIFS files with FUID the fuid is printed in hex followed by
3431 * the domain-rid string.
3433 static void
3434 print_idstr(uint64_t id, const char *id_type)
3436 if (FUID_INDEX(id)) {
3437 const char *domain =
3438 zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
3439 (void) printf("\t%s %llx [%s-%d]\n", id_type,
3440 (u_longlong_t)id, domain, (int)FUID_RID(id));
3441 } else {
3442 (void) printf("\t%s %llu\n", id_type, (u_longlong_t)id);
3447 static void
3448 dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
3450 uint32_t uid_idx, gid_idx;
3452 uid_idx = FUID_INDEX(uid);
3453 gid_idx = FUID_INDEX(gid);
3455 /* Load domain table, if not already loaded */
3456 if (!fuid_table_loaded && (uid_idx || gid_idx)) {
3457 uint64_t fuid_obj;
3459 /* first find the fuid object. It lives in the master node */
3460 VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
3461 8, 1, &fuid_obj) == 0);
3462 zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
3463 (void) zfs_fuid_table_load(os, fuid_obj,
3464 &idx_tree, &domain_tree);
3465 fuid_table_loaded = B_TRUE;
3468 print_idstr(uid, "uid");
3469 print_idstr(gid, "gid");
3472 static void
3473 dump_znode_sa_xattr(sa_handle_t *hdl)
3475 nvlist_t *sa_xattr;
3476 nvpair_t *elem = NULL;
3477 int sa_xattr_size = 0;
3478 int sa_xattr_entries = 0;
3479 int error;
3480 char *sa_xattr_packed;
3482 error = sa_size(hdl, sa_attr_table[ZPL_DXATTR], &sa_xattr_size);
3483 if (error || sa_xattr_size == 0)
3484 return;
3486 sa_xattr_packed = malloc(sa_xattr_size);
3487 if (sa_xattr_packed == NULL)
3488 return;
3490 error = sa_lookup(hdl, sa_attr_table[ZPL_DXATTR],
3491 sa_xattr_packed, sa_xattr_size);
3492 if (error) {
3493 free(sa_xattr_packed);
3494 return;
3497 error = nvlist_unpack(sa_xattr_packed, sa_xattr_size, &sa_xattr, 0);
3498 if (error) {
3499 free(sa_xattr_packed);
3500 return;
3503 while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL)
3504 sa_xattr_entries++;
3506 (void) printf("\tSA xattrs: %d bytes, %d entries\n\n",
3507 sa_xattr_size, sa_xattr_entries);
3508 while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL) {
3509 boolean_t can_print = !dump_opt['P'];
3510 uchar_t *value;
3511 uint_t cnt, idx;
3513 (void) printf("\t\t%s = ", nvpair_name(elem));
3514 nvpair_value_byte_array(elem, &value, &cnt);
3516 for (idx = 0; idx < cnt; ++idx) {
3517 if (!isprint(value[idx])) {
3518 can_print = B_FALSE;
3519 break;
3523 for (idx = 0; idx < cnt; ++idx) {
3524 if (can_print)
3525 (void) putchar(value[idx]);
3526 else
3527 (void) printf("\\%3.3o", value[idx]);
3529 (void) putchar('\n');
3532 nvlist_free(sa_xattr);
3533 free(sa_xattr_packed);
3536 static void
3537 dump_znode_symlink(sa_handle_t *hdl)
3539 int sa_symlink_size = 0;
3540 char linktarget[MAXPATHLEN];
3541 int error;
3543 error = sa_size(hdl, sa_attr_table[ZPL_SYMLINK], &sa_symlink_size);
3544 if (error || sa_symlink_size == 0) {
3545 return;
3547 if (sa_symlink_size >= sizeof (linktarget)) {
3548 (void) printf("symlink size %d is too large\n",
3549 sa_symlink_size);
3550 return;
3552 linktarget[sa_symlink_size] = '\0';
3553 if (sa_lookup(hdl, sa_attr_table[ZPL_SYMLINK],
3554 &linktarget, sa_symlink_size) == 0)
3555 (void) printf("\ttarget %s\n", linktarget);
3558 static void
3559 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
3561 (void) data, (void) size;
3562 char path[MAXPATHLEN * 2]; /* allow for xattr and failure prefix */
3563 sa_handle_t *hdl;
3564 uint64_t xattr, rdev, gen;
3565 uint64_t uid, gid, mode, fsize, parent, links;
3566 uint64_t pflags;
3567 uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
3568 time_t z_crtime, z_atime, z_mtime, z_ctime;
3569 sa_bulk_attr_t bulk[12];
3570 int idx = 0;
3571 int error;
3573 VERIFY3P(os, ==, sa_os);
3574 if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
3575 (void) printf("Failed to get handle for SA znode\n");
3576 return;
3579 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
3580 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
3581 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
3582 &links, 8);
3583 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
3584 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
3585 &mode, 8);
3586 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
3587 NULL, &parent, 8);
3588 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
3589 &fsize, 8);
3590 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
3591 acctm, 16);
3592 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
3593 modtm, 16);
3594 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
3595 crtm, 16);
3596 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
3597 chgtm, 16);
3598 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
3599 &pflags, 8);
3601 if (sa_bulk_lookup(hdl, bulk, idx)) {
3602 (void) sa_handle_destroy(hdl);
3603 return;
3606 z_crtime = (time_t)crtm[0];
3607 z_atime = (time_t)acctm[0];
3608 z_mtime = (time_t)modtm[0];
3609 z_ctime = (time_t)chgtm[0];
3611 if (dump_opt['d'] > 4) {
3612 error = zfs_obj_to_path(os, object, path, sizeof (path));
3613 if (error == ESTALE) {
3614 (void) snprintf(path, sizeof (path), "on delete queue");
3615 } else if (error != 0) {
3616 leaked_objects++;
3617 (void) snprintf(path, sizeof (path),
3618 "path not found, possibly leaked");
3620 (void) printf("\tpath %s\n", path);
3623 if (S_ISLNK(mode))
3624 dump_znode_symlink(hdl);
3625 dump_uidgid(os, uid, gid);
3626 (void) printf("\tatime %s", ctime(&z_atime));
3627 (void) printf("\tmtime %s", ctime(&z_mtime));
3628 (void) printf("\tctime %s", ctime(&z_ctime));
3629 (void) printf("\tcrtime %s", ctime(&z_crtime));
3630 (void) printf("\tgen %llu\n", (u_longlong_t)gen);
3631 (void) printf("\tmode %llo\n", (u_longlong_t)mode);
3632 (void) printf("\tsize %llu\n", (u_longlong_t)fsize);
3633 (void) printf("\tparent %llu\n", (u_longlong_t)parent);
3634 (void) printf("\tlinks %llu\n", (u_longlong_t)links);
3635 (void) printf("\tpflags %llx\n", (u_longlong_t)pflags);
3636 if (dmu_objset_projectquota_enabled(os) && (pflags & ZFS_PROJID)) {
3637 uint64_t projid;
3639 if (sa_lookup(hdl, sa_attr_table[ZPL_PROJID], &projid,
3640 sizeof (uint64_t)) == 0)
3641 (void) printf("\tprojid %llu\n", (u_longlong_t)projid);
3643 if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
3644 sizeof (uint64_t)) == 0)
3645 (void) printf("\txattr %llu\n", (u_longlong_t)xattr);
3646 if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
3647 sizeof (uint64_t)) == 0)
3648 (void) printf("\trdev 0x%016llx\n", (u_longlong_t)rdev);
3649 dump_znode_sa_xattr(hdl);
3650 sa_handle_destroy(hdl);
3653 static void
3654 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
3656 (void) os, (void) object, (void) data, (void) size;
3659 static void
3660 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
3662 (void) os, (void) object, (void) data, (void) size;
3665 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
3666 dump_none, /* unallocated */
3667 dump_zap, /* object directory */
3668 dump_uint64, /* object array */
3669 dump_none, /* packed nvlist */
3670 dump_packed_nvlist, /* packed nvlist size */
3671 dump_none, /* bpobj */
3672 dump_bpobj, /* bpobj header */
3673 dump_none, /* SPA space map header */
3674 dump_none, /* SPA space map */
3675 dump_none, /* ZIL intent log */
3676 dump_dnode, /* DMU dnode */
3677 dump_dmu_objset, /* DMU objset */
3678 dump_dsl_dir, /* DSL directory */
3679 dump_zap, /* DSL directory child map */
3680 dump_zap, /* DSL dataset snap map */
3681 dump_zap, /* DSL props */
3682 dump_dsl_dataset, /* DSL dataset */
3683 dump_znode, /* ZFS znode */
3684 dump_acl, /* ZFS V0 ACL */
3685 dump_uint8, /* ZFS plain file */
3686 dump_zpldir, /* ZFS directory */
3687 dump_zap, /* ZFS master node */
3688 dump_zap, /* ZFS delete queue */
3689 dump_uint8, /* zvol object */
3690 dump_zap, /* zvol prop */
3691 dump_uint8, /* other uint8[] */
3692 dump_uint64, /* other uint64[] */
3693 dump_zap, /* other ZAP */
3694 dump_zap, /* persistent error log */
3695 dump_uint8, /* SPA history */
3696 dump_history_offsets, /* SPA history offsets */
3697 dump_zap, /* Pool properties */
3698 dump_zap, /* DSL permissions */
3699 dump_acl, /* ZFS ACL */
3700 dump_uint8, /* ZFS SYSACL */
3701 dump_none, /* FUID nvlist */
3702 dump_packed_nvlist, /* FUID nvlist size */
3703 dump_zap, /* DSL dataset next clones */
3704 dump_zap, /* DSL scrub queue */
3705 dump_zap, /* ZFS user/group/project used */
3706 dump_zap, /* ZFS user/group/project quota */
3707 dump_zap, /* snapshot refcount tags */
3708 dump_ddt_zap, /* DDT ZAP object */
3709 dump_zap, /* DDT statistics */
3710 dump_znode, /* SA object */
3711 dump_zap, /* SA Master Node */
3712 dump_sa_attrs, /* SA attribute registration */
3713 dump_sa_layouts, /* SA attribute layouts */
3714 dump_zap, /* DSL scrub translations */
3715 dump_none, /* fake dedup BP */
3716 dump_zap, /* deadlist */
3717 dump_none, /* deadlist hdr */
3718 dump_zap, /* dsl clones */
3719 dump_bpobj_subobjs, /* bpobj subobjs */
3720 dump_unknown, /* Unknown type, must be last */
3723 static boolean_t
3724 match_object_type(dmu_object_type_t obj_type, uint64_t flags)
3726 boolean_t match = B_TRUE;
3728 switch (obj_type) {
3729 case DMU_OT_DIRECTORY_CONTENTS:
3730 if (!(flags & ZOR_FLAG_DIRECTORY))
3731 match = B_FALSE;
3732 break;
3733 case DMU_OT_PLAIN_FILE_CONTENTS:
3734 if (!(flags & ZOR_FLAG_PLAIN_FILE))
3735 match = B_FALSE;
3736 break;
3737 case DMU_OT_SPACE_MAP:
3738 if (!(flags & ZOR_FLAG_SPACE_MAP))
3739 match = B_FALSE;
3740 break;
3741 default:
3742 if (strcmp(zdb_ot_name(obj_type), "zap") == 0) {
3743 if (!(flags & ZOR_FLAG_ZAP))
3744 match = B_FALSE;
3745 break;
3749 * If all bits except some of the supported flags are
3750 * set, the user combined the all-types flag (A) with
3751 * a negated flag to exclude some types (e.g. A-f to
3752 * show all object types except plain files).
3754 if ((flags | ZOR_SUPPORTED_FLAGS) != ZOR_FLAG_ALL_TYPES)
3755 match = B_FALSE;
3757 break;
3760 return (match);
3763 static void
3764 dump_object(objset_t *os, uint64_t object, int verbosity,
3765 boolean_t *print_header, uint64_t *dnode_slots_used, uint64_t flags)
3767 dmu_buf_t *db = NULL;
3768 dmu_object_info_t doi;
3769 dnode_t *dn;
3770 boolean_t dnode_held = B_FALSE;
3771 void *bonus = NULL;
3772 size_t bsize = 0;
3773 char iblk[32], dblk[32], lsize[32], asize[32], fill[32], dnsize[32];
3774 char bonus_size[32];
3775 char aux[50];
3776 int error;
3778 /* make sure nicenum has enough space */
3779 _Static_assert(sizeof (iblk) >= NN_NUMBUF_SZ, "iblk truncated");
3780 _Static_assert(sizeof (dblk) >= NN_NUMBUF_SZ, "dblk truncated");
3781 _Static_assert(sizeof (lsize) >= NN_NUMBUF_SZ, "lsize truncated");
3782 _Static_assert(sizeof (asize) >= NN_NUMBUF_SZ, "asize truncated");
3783 _Static_assert(sizeof (bonus_size) >= NN_NUMBUF_SZ,
3784 "bonus_size truncated");
3786 if (*print_header) {
3787 (void) printf("\n%10s %3s %5s %5s %5s %6s %5s %6s %s\n",
3788 "Object", "lvl", "iblk", "dblk", "dsize", "dnsize",
3789 "lsize", "%full", "type");
3790 *print_header = 0;
3793 if (object == 0) {
3794 dn = DMU_META_DNODE(os);
3795 dmu_object_info_from_dnode(dn, &doi);
3796 } else {
3798 * Encrypted datasets will have sensitive bonus buffers
3799 * encrypted. Therefore we cannot hold the bonus buffer and
3800 * must hold the dnode itself instead.
3802 error = dmu_object_info(os, object, &doi);
3803 if (error)
3804 fatal("dmu_object_info() failed, errno %u", error);
3806 if (!key_loaded && os->os_encrypted &&
3807 DMU_OT_IS_ENCRYPTED(doi.doi_bonus_type)) {
3808 error = dnode_hold(os, object, FTAG, &dn);
3809 if (error)
3810 fatal("dnode_hold() failed, errno %u", error);
3811 dnode_held = B_TRUE;
3812 } else {
3813 error = dmu_bonus_hold(os, object, FTAG, &db);
3814 if (error)
3815 fatal("dmu_bonus_hold(%llu) failed, errno %u",
3816 object, error);
3817 bonus = db->db_data;
3818 bsize = db->db_size;
3819 dn = DB_DNODE((dmu_buf_impl_t *)db);
3824 * Default to showing all object types if no flags were specified.
3826 if (flags != 0 && flags != ZOR_FLAG_ALL_TYPES &&
3827 !match_object_type(doi.doi_type, flags))
3828 goto out;
3830 if (dnode_slots_used)
3831 *dnode_slots_used = doi.doi_dnodesize / DNODE_MIN_SIZE;
3833 zdb_nicenum(doi.doi_metadata_block_size, iblk, sizeof (iblk));
3834 zdb_nicenum(doi.doi_data_block_size, dblk, sizeof (dblk));
3835 zdb_nicenum(doi.doi_max_offset, lsize, sizeof (lsize));
3836 zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize, sizeof (asize));
3837 zdb_nicenum(doi.doi_bonus_size, bonus_size, sizeof (bonus_size));
3838 zdb_nicenum(doi.doi_dnodesize, dnsize, sizeof (dnsize));
3839 (void) snprintf(fill, sizeof (fill), "%6.2f", 100.0 *
3840 doi.doi_fill_count * doi.doi_data_block_size / (object == 0 ?
3841 DNODES_PER_BLOCK : 1) / doi.doi_max_offset);
3843 aux[0] = '\0';
3845 if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
3846 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
3847 " (K=%s)", ZDB_CHECKSUM_NAME(doi.doi_checksum));
3850 if (doi.doi_compress == ZIO_COMPRESS_INHERIT &&
3851 ZIO_COMPRESS_HASLEVEL(os->os_compress) && verbosity >= 6) {
3852 const char *compname = NULL;
3853 if (zfs_prop_index_to_string(ZFS_PROP_COMPRESSION,
3854 ZIO_COMPRESS_RAW(os->os_compress, os->os_complevel),
3855 &compname) == 0) {
3856 (void) snprintf(aux + strlen(aux),
3857 sizeof (aux) - strlen(aux), " (Z=inherit=%s)",
3858 compname);
3859 } else {
3860 (void) snprintf(aux + strlen(aux),
3861 sizeof (aux) - strlen(aux),
3862 " (Z=inherit=%s-unknown)",
3863 ZDB_COMPRESS_NAME(os->os_compress));
3865 } else if (doi.doi_compress == ZIO_COMPRESS_INHERIT && verbosity >= 6) {
3866 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
3867 " (Z=inherit=%s)", ZDB_COMPRESS_NAME(os->os_compress));
3868 } else if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
3869 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
3870 " (Z=%s)", ZDB_COMPRESS_NAME(doi.doi_compress));
3873 (void) printf("%10lld %3u %5s %5s %5s %6s %5s %6s %s%s\n",
3874 (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
3875 asize, dnsize, lsize, fill, zdb_ot_name(doi.doi_type), aux);
3877 if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
3878 (void) printf("%10s %3s %5s %5s %5s %5s %5s %6s %s\n",
3879 "", "", "", "", "", "", bonus_size, "bonus",
3880 zdb_ot_name(doi.doi_bonus_type));
3883 if (verbosity >= 4) {
3884 (void) printf("\tdnode flags: %s%s%s%s\n",
3885 (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
3886 "USED_BYTES " : "",
3887 (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
3888 "USERUSED_ACCOUNTED " : "",
3889 (dn->dn_phys->dn_flags & DNODE_FLAG_USEROBJUSED_ACCOUNTED) ?
3890 "USEROBJUSED_ACCOUNTED " : "",
3891 (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
3892 "SPILL_BLKPTR" : "");
3893 (void) printf("\tdnode maxblkid: %llu\n",
3894 (longlong_t)dn->dn_phys->dn_maxblkid);
3896 if (!dnode_held) {
3897 object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os,
3898 object, bonus, bsize);
3899 } else {
3900 (void) printf("\t\t(bonus encrypted)\n");
3903 if (key_loaded ||
3904 (!os->os_encrypted || !DMU_OT_IS_ENCRYPTED(doi.doi_type))) {
3905 object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object,
3906 NULL, 0);
3907 } else {
3908 (void) printf("\t\t(object encrypted)\n");
3911 *print_header = B_TRUE;
3914 if (verbosity >= 5) {
3915 if (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
3916 char blkbuf[BP_SPRINTF_LEN];
3917 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf),
3918 DN_SPILL_BLKPTR(dn->dn_phys), B_FALSE);
3919 (void) printf("\nSpill block: %s\n", blkbuf);
3921 dump_indirect(dn);
3924 if (verbosity >= 5) {
3926 * Report the list of segments that comprise the object.
3928 uint64_t start = 0;
3929 uint64_t end;
3930 uint64_t blkfill = 1;
3931 int minlvl = 1;
3933 if (dn->dn_type == DMU_OT_DNODE) {
3934 minlvl = 0;
3935 blkfill = DNODES_PER_BLOCK;
3938 for (;;) {
3939 char segsize[32];
3940 /* make sure nicenum has enough space */
3941 _Static_assert(sizeof (segsize) >= NN_NUMBUF_SZ,
3942 "segsize truncated");
3943 error = dnode_next_offset(dn,
3944 0, &start, minlvl, blkfill, 0);
3945 if (error)
3946 break;
3947 end = start;
3948 error = dnode_next_offset(dn,
3949 DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
3950 zdb_nicenum(end - start, segsize, sizeof (segsize));
3951 (void) printf("\t\tsegment [%016llx, %016llx)"
3952 " size %5s\n", (u_longlong_t)start,
3953 (u_longlong_t)end, segsize);
3954 if (error)
3955 break;
3956 start = end;
3960 out:
3961 if (db != NULL)
3962 dmu_buf_rele(db, FTAG);
3963 if (dnode_held)
3964 dnode_rele(dn, FTAG);
3967 static void
3968 count_dir_mos_objects(dsl_dir_t *dd)
3970 mos_obj_refd(dd->dd_object);
3971 mos_obj_refd(dsl_dir_phys(dd)->dd_child_dir_zapobj);
3972 mos_obj_refd(dsl_dir_phys(dd)->dd_deleg_zapobj);
3973 mos_obj_refd(dsl_dir_phys(dd)->dd_props_zapobj);
3974 mos_obj_refd(dsl_dir_phys(dd)->dd_clones);
3977 * The dd_crypto_obj can be referenced by multiple dsl_dir's.
3978 * Ignore the references after the first one.
3980 mos_obj_refd_multiple(dd->dd_crypto_obj);
3983 static void
3984 count_ds_mos_objects(dsl_dataset_t *ds)
3986 mos_obj_refd(ds->ds_object);
3987 mos_obj_refd(dsl_dataset_phys(ds)->ds_next_clones_obj);
3988 mos_obj_refd(dsl_dataset_phys(ds)->ds_props_obj);
3989 mos_obj_refd(dsl_dataset_phys(ds)->ds_userrefs_obj);
3990 mos_obj_refd(dsl_dataset_phys(ds)->ds_snapnames_zapobj);
3991 mos_obj_refd(ds->ds_bookmarks_obj);
3993 if (!dsl_dataset_is_snapshot(ds)) {
3994 count_dir_mos_objects(ds->ds_dir);
3998 static const char *const objset_types[DMU_OST_NUMTYPES] = {
3999 "NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
4002 * Parse a string denoting a range of object IDs of the form
4003 * <start>[:<end>[:flags]], and store the results in zor.
4004 * Return 0 on success. On error, return 1 and update the msg
4005 * pointer to point to a descriptive error message.
4007 static int
4008 parse_object_range(char *range, zopt_object_range_t *zor, const char **msg)
4010 uint64_t flags = 0;
4011 char *p, *s, *dup, *flagstr, *tmp = NULL;
4012 size_t len;
4013 int i;
4014 int rc = 0;
4016 if (strchr(range, ':') == NULL) {
4017 zor->zor_obj_start = strtoull(range, &p, 0);
4018 if (*p != '\0') {
4019 *msg = "Invalid characters in object ID";
4020 rc = 1;
4022 zor->zor_obj_start = ZDB_MAP_OBJECT_ID(zor->zor_obj_start);
4023 zor->zor_obj_end = zor->zor_obj_start;
4024 return (rc);
4027 if (strchr(range, ':') == range) {
4028 *msg = "Invalid leading colon";
4029 rc = 1;
4030 return (rc);
4033 len = strlen(range);
4034 if (range[len - 1] == ':') {
4035 *msg = "Invalid trailing colon";
4036 rc = 1;
4037 return (rc);
4040 dup = strdup(range);
4041 s = strtok_r(dup, ":", &tmp);
4042 zor->zor_obj_start = strtoull(s, &p, 0);
4044 if (*p != '\0') {
4045 *msg = "Invalid characters in start object ID";
4046 rc = 1;
4047 goto out;
4050 s = strtok_r(NULL, ":", &tmp);
4051 zor->zor_obj_end = strtoull(s, &p, 0);
4053 if (*p != '\0') {
4054 *msg = "Invalid characters in end object ID";
4055 rc = 1;
4056 goto out;
4059 if (zor->zor_obj_start > zor->zor_obj_end) {
4060 *msg = "Start object ID may not exceed end object ID";
4061 rc = 1;
4062 goto out;
4065 s = strtok_r(NULL, ":", &tmp);
4066 if (s == NULL) {
4067 zor->zor_flags = ZOR_FLAG_ALL_TYPES;
4068 goto out;
4069 } else if (strtok_r(NULL, ":", &tmp) != NULL) {
4070 *msg = "Invalid colon-delimited field after flags";
4071 rc = 1;
4072 goto out;
4075 flagstr = s;
4076 for (i = 0; flagstr[i]; i++) {
4077 int bit;
4078 boolean_t negation = (flagstr[i] == '-');
4080 if (negation) {
4081 i++;
4082 if (flagstr[i] == '\0') {
4083 *msg = "Invalid trailing negation operator";
4084 rc = 1;
4085 goto out;
4088 bit = flagbits[(uchar_t)flagstr[i]];
4089 if (bit == 0) {
4090 *msg = "Invalid flag";
4091 rc = 1;
4092 goto out;
4094 if (negation)
4095 flags &= ~bit;
4096 else
4097 flags |= bit;
4099 zor->zor_flags = flags;
4101 zor->zor_obj_start = ZDB_MAP_OBJECT_ID(zor->zor_obj_start);
4102 zor->zor_obj_end = ZDB_MAP_OBJECT_ID(zor->zor_obj_end);
4104 out:
4105 free(dup);
4106 return (rc);
4109 static void
4110 dump_objset(objset_t *os)
4112 dmu_objset_stats_t dds = { 0 };
4113 uint64_t object, object_count;
4114 uint64_t refdbytes, usedobjs, scratch;
4115 char numbuf[32];
4116 char blkbuf[BP_SPRINTF_LEN + 20];
4117 char osname[ZFS_MAX_DATASET_NAME_LEN];
4118 const char *type = "UNKNOWN";
4119 int verbosity = dump_opt['d'];
4120 boolean_t print_header;
4121 unsigned i;
4122 int error;
4123 uint64_t total_slots_used = 0;
4124 uint64_t max_slot_used = 0;
4125 uint64_t dnode_slots;
4126 uint64_t obj_start;
4127 uint64_t obj_end;
4128 uint64_t flags;
4130 /* make sure nicenum has enough space */
4131 _Static_assert(sizeof (numbuf) >= NN_NUMBUF_SZ, "numbuf truncated");
4133 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
4134 dmu_objset_fast_stat(os, &dds);
4135 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
4137 print_header = B_TRUE;
4139 if (dds.dds_type < DMU_OST_NUMTYPES)
4140 type = objset_types[dds.dds_type];
4142 if (dds.dds_type == DMU_OST_META) {
4143 dds.dds_creation_txg = TXG_INITIAL;
4144 usedobjs = BP_GET_FILL(os->os_rootbp);
4145 refdbytes = dsl_dir_phys(os->os_spa->spa_dsl_pool->dp_mos_dir)->
4146 dd_used_bytes;
4147 } else {
4148 dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
4151 ASSERT3U(usedobjs, ==, BP_GET_FILL(os->os_rootbp));
4153 zdb_nicenum(refdbytes, numbuf, sizeof (numbuf));
4155 if (verbosity >= 4) {
4156 (void) snprintf(blkbuf, sizeof (blkbuf), ", rootbp ");
4157 (void) snprintf_blkptr(blkbuf + strlen(blkbuf),
4158 sizeof (blkbuf) - strlen(blkbuf), os->os_rootbp);
4159 } else {
4160 blkbuf[0] = '\0';
4163 dmu_objset_name(os, osname);
4165 (void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
4166 "%s, %llu objects%s%s\n",
4167 osname, type, (u_longlong_t)dmu_objset_id(os),
4168 (u_longlong_t)dds.dds_creation_txg,
4169 numbuf, (u_longlong_t)usedobjs, blkbuf,
4170 (dds.dds_inconsistent) ? " (inconsistent)" : "");
4172 for (i = 0; i < zopt_object_args; i++) {
4173 obj_start = zopt_object_ranges[i].zor_obj_start;
4174 obj_end = zopt_object_ranges[i].zor_obj_end;
4175 flags = zopt_object_ranges[i].zor_flags;
4177 object = obj_start;
4178 if (object == 0 || obj_start == obj_end)
4179 dump_object(os, object, verbosity, &print_header, NULL,
4180 flags);
4181 else
4182 object--;
4184 while ((dmu_object_next(os, &object, B_FALSE, 0) == 0) &&
4185 object <= obj_end) {
4186 dump_object(os, object, verbosity, &print_header, NULL,
4187 flags);
4191 if (zopt_object_args > 0) {
4192 (void) printf("\n");
4193 return;
4196 if (dump_opt['i'] != 0 || verbosity >= 2)
4197 dump_intent_log(dmu_objset_zil(os));
4199 if (dmu_objset_ds(os) != NULL) {
4200 dsl_dataset_t *ds = dmu_objset_ds(os);
4201 dump_blkptr_list(&ds->ds_deadlist, "Deadlist");
4202 if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist) &&
4203 !dmu_objset_is_snapshot(os)) {
4204 dump_blkptr_list(&ds->ds_dir->dd_livelist, "Livelist");
4205 if (verify_dd_livelist(os) != 0)
4206 fatal("livelist is incorrect");
4209 if (dsl_dataset_remap_deadlist_exists(ds)) {
4210 (void) printf("ds_remap_deadlist:\n");
4211 dump_blkptr_list(&ds->ds_remap_deadlist, "Deadlist");
4213 count_ds_mos_objects(ds);
4216 if (dmu_objset_ds(os) != NULL)
4217 dump_bookmarks(os, verbosity);
4219 if (verbosity < 2)
4220 return;
4222 if (BP_IS_HOLE(os->os_rootbp))
4223 return;
4225 dump_object(os, 0, verbosity, &print_header, NULL, 0);
4226 object_count = 0;
4227 if (DMU_USERUSED_DNODE(os) != NULL &&
4228 DMU_USERUSED_DNODE(os)->dn_type != 0) {
4229 dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header,
4230 NULL, 0);
4231 dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header,
4232 NULL, 0);
4235 if (DMU_PROJECTUSED_DNODE(os) != NULL &&
4236 DMU_PROJECTUSED_DNODE(os)->dn_type != 0)
4237 dump_object(os, DMU_PROJECTUSED_OBJECT, verbosity,
4238 &print_header, NULL, 0);
4240 object = 0;
4241 while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
4242 dump_object(os, object, verbosity, &print_header, &dnode_slots,
4244 object_count++;
4245 total_slots_used += dnode_slots;
4246 max_slot_used = object + dnode_slots - 1;
4249 (void) printf("\n");
4251 (void) printf(" Dnode slots:\n");
4252 (void) printf("\tTotal used: %10llu\n",
4253 (u_longlong_t)total_slots_used);
4254 (void) printf("\tMax used: %10llu\n",
4255 (u_longlong_t)max_slot_used);
4256 (void) printf("\tPercent empty: %10lf\n",
4257 (double)(max_slot_used - total_slots_used)*100 /
4258 (double)max_slot_used);
4259 (void) printf("\n");
4261 if (error != ESRCH) {
4262 (void) fprintf(stderr, "dmu_object_next() = %d\n", error);
4263 abort();
4266 ASSERT3U(object_count, ==, usedobjs);
4268 if (leaked_objects != 0) {
4269 (void) printf("%d potentially leaked objects detected\n",
4270 leaked_objects);
4271 leaked_objects = 0;
4275 static void
4276 dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
4278 time_t timestamp = ub->ub_timestamp;
4280 (void) printf("%s", header ? header : "");
4281 (void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
4282 (void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
4283 (void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
4284 (void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
4285 (void) printf("\ttimestamp = %llu UTC = %s",
4286 (u_longlong_t)ub->ub_timestamp, ctime(&timestamp));
4288 char blkbuf[BP_SPRINTF_LEN];
4289 snprintf_blkptr(blkbuf, sizeof (blkbuf), &ub->ub_rootbp);
4290 (void) printf("\tbp = %s\n", blkbuf);
4292 (void) printf("\tmmp_magic = %016llx\n",
4293 (u_longlong_t)ub->ub_mmp_magic);
4294 if (MMP_VALID(ub)) {
4295 (void) printf("\tmmp_delay = %0llu\n",
4296 (u_longlong_t)ub->ub_mmp_delay);
4297 if (MMP_SEQ_VALID(ub))
4298 (void) printf("\tmmp_seq = %u\n",
4299 (unsigned int) MMP_SEQ(ub));
4300 if (MMP_FAIL_INT_VALID(ub))
4301 (void) printf("\tmmp_fail = %u\n",
4302 (unsigned int) MMP_FAIL_INT(ub));
4303 if (MMP_INTERVAL_VALID(ub))
4304 (void) printf("\tmmp_write = %u\n",
4305 (unsigned int) MMP_INTERVAL(ub));
4306 /* After MMP_* to make summarize_uberblock_mmp cleaner */
4307 (void) printf("\tmmp_valid = %x\n",
4308 (unsigned int) ub->ub_mmp_config & 0xFF);
4311 if (dump_opt['u'] >= 4) {
4312 char blkbuf[BP_SPRINTF_LEN];
4313 snprintf_blkptr(blkbuf, sizeof (blkbuf), &ub->ub_rootbp);
4314 (void) printf("\trootbp = %s\n", blkbuf);
4316 (void) printf("\tcheckpoint_txg = %llu\n",
4317 (u_longlong_t)ub->ub_checkpoint_txg);
4319 (void) printf("\traidz_reflow state=%u off=%llu\n",
4320 (int)RRSS_GET_STATE(ub),
4321 (u_longlong_t)RRSS_GET_OFFSET(ub));
4323 (void) printf("%s", footer ? footer : "");
4326 static void
4327 dump_config(spa_t *spa)
4329 dmu_buf_t *db;
4330 size_t nvsize = 0;
4331 int error = 0;
4334 error = dmu_bonus_hold(spa->spa_meta_objset,
4335 spa->spa_config_object, FTAG, &db);
4337 if (error == 0) {
4338 nvsize = *(uint64_t *)db->db_data;
4339 dmu_buf_rele(db, FTAG);
4341 (void) printf("\nMOS Configuration:\n");
4342 dump_packed_nvlist(spa->spa_meta_objset,
4343 spa->spa_config_object, (void *)&nvsize, 1);
4344 } else {
4345 (void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
4346 (u_longlong_t)spa->spa_config_object, error);
4350 static void
4351 dump_cachefile(const char *cachefile)
4353 int fd;
4354 struct stat64 statbuf;
4355 char *buf;
4356 nvlist_t *config;
4358 if ((fd = open64(cachefile, O_RDONLY)) < 0) {
4359 (void) printf("cannot open '%s': %s\n", cachefile,
4360 strerror(errno));
4361 zdb_exit(1);
4364 if (fstat64(fd, &statbuf) != 0) {
4365 (void) printf("failed to stat '%s': %s\n", cachefile,
4366 strerror(errno));
4367 zdb_exit(1);
4370 if ((buf = malloc(statbuf.st_size)) == NULL) {
4371 (void) fprintf(stderr, "failed to allocate %llu bytes\n",
4372 (u_longlong_t)statbuf.st_size);
4373 zdb_exit(1);
4376 if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
4377 (void) fprintf(stderr, "failed to read %llu bytes\n",
4378 (u_longlong_t)statbuf.st_size);
4379 zdb_exit(1);
4382 (void) close(fd);
4384 if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
4385 (void) fprintf(stderr, "failed to unpack nvlist\n");
4386 zdb_exit(1);
4389 free(buf);
4391 dump_nvlist(config, 0);
4393 nvlist_free(config);
4397 * ZFS label nvlist stats
4399 typedef struct zdb_nvl_stats {
4400 int zns_list_count;
4401 int zns_leaf_count;
4402 size_t zns_leaf_largest;
4403 size_t zns_leaf_total;
4404 nvlist_t *zns_string;
4405 nvlist_t *zns_uint64;
4406 nvlist_t *zns_boolean;
4407 } zdb_nvl_stats_t;
4409 static void
4410 collect_nvlist_stats(nvlist_t *nvl, zdb_nvl_stats_t *stats)
4412 nvlist_t *list, **array;
4413 nvpair_t *nvp = NULL;
4414 const char *name;
4415 uint_t i, items;
4417 stats->zns_list_count++;
4419 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4420 name = nvpair_name(nvp);
4422 switch (nvpair_type(nvp)) {
4423 case DATA_TYPE_STRING:
4424 fnvlist_add_string(stats->zns_string, name,
4425 fnvpair_value_string(nvp));
4426 break;
4427 case DATA_TYPE_UINT64:
4428 fnvlist_add_uint64(stats->zns_uint64, name,
4429 fnvpair_value_uint64(nvp));
4430 break;
4431 case DATA_TYPE_BOOLEAN:
4432 fnvlist_add_boolean(stats->zns_boolean, name);
4433 break;
4434 case DATA_TYPE_NVLIST:
4435 if (nvpair_value_nvlist(nvp, &list) == 0)
4436 collect_nvlist_stats(list, stats);
4437 break;
4438 case DATA_TYPE_NVLIST_ARRAY:
4439 if (nvpair_value_nvlist_array(nvp, &array, &items) != 0)
4440 break;
4442 for (i = 0; i < items; i++) {
4443 collect_nvlist_stats(array[i], stats);
4445 /* collect stats on leaf vdev */
4446 if (strcmp(name, "children") == 0) {
4447 size_t size;
4449 (void) nvlist_size(array[i], &size,
4450 NV_ENCODE_XDR);
4451 stats->zns_leaf_total += size;
4452 if (size > stats->zns_leaf_largest)
4453 stats->zns_leaf_largest = size;
4454 stats->zns_leaf_count++;
4457 break;
4458 default:
4459 (void) printf("skip type %d!\n", (int)nvpair_type(nvp));
4464 static void
4465 dump_nvlist_stats(nvlist_t *nvl, size_t cap)
4467 zdb_nvl_stats_t stats = { 0 };
4468 size_t size, sum = 0, total;
4469 size_t noise;
4471 /* requires nvlist with non-unique names for stat collection */
4472 VERIFY0(nvlist_alloc(&stats.zns_string, 0, 0));
4473 VERIFY0(nvlist_alloc(&stats.zns_uint64, 0, 0));
4474 VERIFY0(nvlist_alloc(&stats.zns_boolean, 0, 0));
4475 VERIFY0(nvlist_size(stats.zns_boolean, &noise, NV_ENCODE_XDR));
4477 (void) printf("\n\nZFS Label NVList Config Stats:\n");
4479 VERIFY0(nvlist_size(nvl, &total, NV_ENCODE_XDR));
4480 (void) printf(" %d bytes used, %d bytes free (using %4.1f%%)\n\n",
4481 (int)total, (int)(cap - total), 100.0 * total / cap);
4483 collect_nvlist_stats(nvl, &stats);
4485 VERIFY0(nvlist_size(stats.zns_uint64, &size, NV_ENCODE_XDR));
4486 size -= noise;
4487 sum += size;
4488 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "integers:",
4489 (int)fnvlist_num_pairs(stats.zns_uint64),
4490 (int)size, 100.0 * size / total);
4492 VERIFY0(nvlist_size(stats.zns_string, &size, NV_ENCODE_XDR));
4493 size -= noise;
4494 sum += size;
4495 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "strings:",
4496 (int)fnvlist_num_pairs(stats.zns_string),
4497 (int)size, 100.0 * size / total);
4499 VERIFY0(nvlist_size(stats.zns_boolean, &size, NV_ENCODE_XDR));
4500 size -= noise;
4501 sum += size;
4502 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "booleans:",
4503 (int)fnvlist_num_pairs(stats.zns_boolean),
4504 (int)size, 100.0 * size / total);
4506 size = total - sum; /* treat remainder as nvlist overhead */
4507 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n\n", "nvlists:",
4508 stats.zns_list_count, (int)size, 100.0 * size / total);
4510 if (stats.zns_leaf_count > 0) {
4511 size_t average = stats.zns_leaf_total / stats.zns_leaf_count;
4513 (void) printf("%12s %4d %6d bytes average\n", "leaf vdevs:",
4514 stats.zns_leaf_count, (int)average);
4515 (void) printf("%24d bytes largest\n",
4516 (int)stats.zns_leaf_largest);
4518 if (dump_opt['l'] >= 3 && average > 0)
4519 (void) printf(" space for %d additional leaf vdevs\n",
4520 (int)((cap - total) / average));
4522 (void) printf("\n");
4524 nvlist_free(stats.zns_string);
4525 nvlist_free(stats.zns_uint64);
4526 nvlist_free(stats.zns_boolean);
4529 typedef struct cksum_record {
4530 zio_cksum_t cksum;
4531 boolean_t labels[VDEV_LABELS];
4532 avl_node_t link;
4533 } cksum_record_t;
4535 static int
4536 cksum_record_compare(const void *x1, const void *x2)
4538 const cksum_record_t *l = (cksum_record_t *)x1;
4539 const cksum_record_t *r = (cksum_record_t *)x2;
4540 int arraysize = ARRAY_SIZE(l->cksum.zc_word);
4541 int difference = 0;
4543 for (int i = 0; i < arraysize; i++) {
4544 difference = TREE_CMP(l->cksum.zc_word[i], r->cksum.zc_word[i]);
4545 if (difference)
4546 break;
4549 return (difference);
4552 static cksum_record_t *
4553 cksum_record_alloc(zio_cksum_t *cksum, int l)
4555 cksum_record_t *rec;
4557 rec = umem_zalloc(sizeof (*rec), UMEM_NOFAIL);
4558 rec->cksum = *cksum;
4559 rec->labels[l] = B_TRUE;
4561 return (rec);
4564 static cksum_record_t *
4565 cksum_record_lookup(avl_tree_t *tree, zio_cksum_t *cksum)
4567 cksum_record_t lookup = { .cksum = *cksum };
4568 avl_index_t where;
4570 return (avl_find(tree, &lookup, &where));
4573 static cksum_record_t *
4574 cksum_record_insert(avl_tree_t *tree, zio_cksum_t *cksum, int l)
4576 cksum_record_t *rec;
4578 rec = cksum_record_lookup(tree, cksum);
4579 if (rec) {
4580 rec->labels[l] = B_TRUE;
4581 } else {
4582 rec = cksum_record_alloc(cksum, l);
4583 avl_add(tree, rec);
4586 return (rec);
4589 static int
4590 first_label(cksum_record_t *rec)
4592 for (int i = 0; i < VDEV_LABELS; i++)
4593 if (rec->labels[i])
4594 return (i);
4596 return (-1);
4599 static void
4600 print_label_numbers(const char *prefix, const cksum_record_t *rec)
4602 fputs(prefix, stdout);
4603 for (int i = 0; i < VDEV_LABELS; i++)
4604 if (rec->labels[i] == B_TRUE)
4605 printf("%d ", i);
4606 putchar('\n');
4609 #define MAX_UBERBLOCK_COUNT (VDEV_UBERBLOCK_RING >> UBERBLOCK_SHIFT)
4611 typedef struct zdb_label {
4612 vdev_label_t label;
4613 uint64_t label_offset;
4614 nvlist_t *config_nv;
4615 cksum_record_t *config;
4616 cksum_record_t *uberblocks[MAX_UBERBLOCK_COUNT];
4617 boolean_t header_printed;
4618 boolean_t read_failed;
4619 boolean_t cksum_valid;
4620 } zdb_label_t;
4622 static void
4623 print_label_header(zdb_label_t *label, int l)
4626 if (dump_opt['q'])
4627 return;
4629 if (label->header_printed == B_TRUE)
4630 return;
4632 (void) printf("------------------------------------\n");
4633 (void) printf("LABEL %d %s\n", l,
4634 label->cksum_valid ? "" : "(Bad label cksum)");
4635 (void) printf("------------------------------------\n");
4637 label->header_printed = B_TRUE;
4640 static void
4641 print_l2arc_header(void)
4643 (void) printf("------------------------------------\n");
4644 (void) printf("L2ARC device header\n");
4645 (void) printf("------------------------------------\n");
4648 static void
4649 print_l2arc_log_blocks(void)
4651 (void) printf("------------------------------------\n");
4652 (void) printf("L2ARC device log blocks\n");
4653 (void) printf("------------------------------------\n");
4656 static void
4657 dump_l2arc_log_entries(uint64_t log_entries,
4658 l2arc_log_ent_phys_t *le, uint64_t i)
4660 for (int j = 0; j < log_entries; j++) {
4661 dva_t dva = le[j].le_dva;
4662 (void) printf("lb[%4llu]\tle[%4d]\tDVA asize: %llu, "
4663 "vdev: %llu, offset: %llu\n",
4664 (u_longlong_t)i, j + 1,
4665 (u_longlong_t)DVA_GET_ASIZE(&dva),
4666 (u_longlong_t)DVA_GET_VDEV(&dva),
4667 (u_longlong_t)DVA_GET_OFFSET(&dva));
4668 (void) printf("|\t\t\t\tbirth: %llu\n",
4669 (u_longlong_t)le[j].le_birth);
4670 (void) printf("|\t\t\t\tlsize: %llu\n",
4671 (u_longlong_t)L2BLK_GET_LSIZE((&le[j])->le_prop));
4672 (void) printf("|\t\t\t\tpsize: %llu\n",
4673 (u_longlong_t)L2BLK_GET_PSIZE((&le[j])->le_prop));
4674 (void) printf("|\t\t\t\tcompr: %llu\n",
4675 (u_longlong_t)L2BLK_GET_COMPRESS((&le[j])->le_prop));
4676 (void) printf("|\t\t\t\tcomplevel: %llu\n",
4677 (u_longlong_t)(&le[j])->le_complevel);
4678 (void) printf("|\t\t\t\ttype: %llu\n",
4679 (u_longlong_t)L2BLK_GET_TYPE((&le[j])->le_prop));
4680 (void) printf("|\t\t\t\tprotected: %llu\n",
4681 (u_longlong_t)L2BLK_GET_PROTECTED((&le[j])->le_prop));
4682 (void) printf("|\t\t\t\tprefetch: %llu\n",
4683 (u_longlong_t)L2BLK_GET_PREFETCH((&le[j])->le_prop));
4684 (void) printf("|\t\t\t\taddress: %llu\n",
4685 (u_longlong_t)le[j].le_daddr);
4686 (void) printf("|\t\t\t\tARC state: %llu\n",
4687 (u_longlong_t)L2BLK_GET_STATE((&le[j])->le_prop));
4688 (void) printf("|\n");
4690 (void) printf("\n");
4693 static void
4694 dump_l2arc_log_blkptr(const l2arc_log_blkptr_t *lbps)
4696 (void) printf("|\t\tdaddr: %llu\n", (u_longlong_t)lbps->lbp_daddr);
4697 (void) printf("|\t\tpayload_asize: %llu\n",
4698 (u_longlong_t)lbps->lbp_payload_asize);
4699 (void) printf("|\t\tpayload_start: %llu\n",
4700 (u_longlong_t)lbps->lbp_payload_start);
4701 (void) printf("|\t\tlsize: %llu\n",
4702 (u_longlong_t)L2BLK_GET_LSIZE(lbps->lbp_prop));
4703 (void) printf("|\t\tasize: %llu\n",
4704 (u_longlong_t)L2BLK_GET_PSIZE(lbps->lbp_prop));
4705 (void) printf("|\t\tcompralgo: %llu\n",
4706 (u_longlong_t)L2BLK_GET_COMPRESS(lbps->lbp_prop));
4707 (void) printf("|\t\tcksumalgo: %llu\n",
4708 (u_longlong_t)L2BLK_GET_CHECKSUM(lbps->lbp_prop));
4709 (void) printf("|\n\n");
4712 static void
4713 dump_l2arc_log_blocks(int fd, const l2arc_dev_hdr_phys_t *l2dhdr,
4714 l2arc_dev_hdr_phys_t *rebuild)
4716 l2arc_log_blk_phys_t this_lb;
4717 uint64_t asize;
4718 l2arc_log_blkptr_t lbps[2];
4719 zio_cksum_t cksum;
4720 int failed = 0;
4721 l2arc_dev_t dev;
4723 if (!dump_opt['q'])
4724 print_l2arc_log_blocks();
4725 memcpy(lbps, l2dhdr->dh_start_lbps, sizeof (lbps));
4727 dev.l2ad_evict = l2dhdr->dh_evict;
4728 dev.l2ad_start = l2dhdr->dh_start;
4729 dev.l2ad_end = l2dhdr->dh_end;
4731 if (l2dhdr->dh_start_lbps[0].lbp_daddr == 0) {
4732 /* no log blocks to read */
4733 if (!dump_opt['q']) {
4734 (void) printf("No log blocks to read\n");
4735 (void) printf("\n");
4737 return;
4738 } else {
4739 dev.l2ad_hand = lbps[0].lbp_daddr +
4740 L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
4743 dev.l2ad_first = !!(l2dhdr->dh_flags & L2ARC_DEV_HDR_EVICT_FIRST);
4745 for (;;) {
4746 if (!l2arc_log_blkptr_valid(&dev, &lbps[0]))
4747 break;
4749 /* L2BLK_GET_PSIZE returns aligned size for log blocks */
4750 asize = L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
4751 if (pread64(fd, &this_lb, asize, lbps[0].lbp_daddr) != asize) {
4752 if (!dump_opt['q']) {
4753 (void) printf("Error while reading next log "
4754 "block\n\n");
4756 break;
4759 fletcher_4_native_varsize(&this_lb, asize, &cksum);
4760 if (!ZIO_CHECKSUM_EQUAL(cksum, lbps[0].lbp_cksum)) {
4761 failed++;
4762 if (!dump_opt['q']) {
4763 (void) printf("Invalid cksum\n");
4764 dump_l2arc_log_blkptr(&lbps[0]);
4766 break;
4769 switch (L2BLK_GET_COMPRESS((&lbps[0])->lbp_prop)) {
4770 case ZIO_COMPRESS_OFF:
4771 break;
4772 default: {
4773 abd_t *abd = abd_alloc_linear(asize, B_TRUE);
4774 abd_copy_from_buf_off(abd, &this_lb, 0, asize);
4775 abd_t dabd;
4776 abd_get_from_buf_struct(&dabd, &this_lb,
4777 sizeof (this_lb));
4778 int err = zio_decompress_data(L2BLK_GET_COMPRESS(
4779 (&lbps[0])->lbp_prop), abd, &dabd,
4780 asize, sizeof (this_lb), NULL);
4781 abd_free(&dabd);
4782 abd_free(abd);
4783 if (err != 0) {
4784 (void) printf("L2ARC block decompression "
4785 "failed\n");
4786 goto out;
4788 break;
4792 if (this_lb.lb_magic == BSWAP_64(L2ARC_LOG_BLK_MAGIC))
4793 byteswap_uint64_array(&this_lb, sizeof (this_lb));
4794 if (this_lb.lb_magic != L2ARC_LOG_BLK_MAGIC) {
4795 if (!dump_opt['q'])
4796 (void) printf("Invalid log block magic\n\n");
4797 break;
4800 rebuild->dh_lb_count++;
4801 rebuild->dh_lb_asize += asize;
4802 if (dump_opt['l'] > 1 && !dump_opt['q']) {
4803 (void) printf("lb[%4llu]\tmagic: %llu\n",
4804 (u_longlong_t)rebuild->dh_lb_count,
4805 (u_longlong_t)this_lb.lb_magic);
4806 dump_l2arc_log_blkptr(&lbps[0]);
4809 if (dump_opt['l'] > 2 && !dump_opt['q'])
4810 dump_l2arc_log_entries(l2dhdr->dh_log_entries,
4811 this_lb.lb_entries,
4812 rebuild->dh_lb_count);
4814 if (l2arc_range_check_overlap(lbps[1].lbp_payload_start,
4815 lbps[0].lbp_payload_start, dev.l2ad_evict) &&
4816 !dev.l2ad_first)
4817 break;
4819 lbps[0] = lbps[1];
4820 lbps[1] = this_lb.lb_prev_lbp;
4822 out:
4823 if (!dump_opt['q']) {
4824 (void) printf("log_blk_count:\t %llu with valid cksum\n",
4825 (u_longlong_t)rebuild->dh_lb_count);
4826 (void) printf("\t\t %d with invalid cksum\n", failed);
4827 (void) printf("log_blk_asize:\t %llu\n\n",
4828 (u_longlong_t)rebuild->dh_lb_asize);
4832 static int
4833 dump_l2arc_header(int fd)
4835 l2arc_dev_hdr_phys_t l2dhdr = {0}, rebuild = {0};
4836 int error = B_FALSE;
4838 if (pread64(fd, &l2dhdr, sizeof (l2dhdr),
4839 VDEV_LABEL_START_SIZE) != sizeof (l2dhdr)) {
4840 error = B_TRUE;
4841 } else {
4842 if (l2dhdr.dh_magic == BSWAP_64(L2ARC_DEV_HDR_MAGIC))
4843 byteswap_uint64_array(&l2dhdr, sizeof (l2dhdr));
4845 if (l2dhdr.dh_magic != L2ARC_DEV_HDR_MAGIC)
4846 error = B_TRUE;
4849 if (error) {
4850 (void) printf("L2ARC device header not found\n\n");
4851 /* Do not return an error here for backward compatibility */
4852 return (0);
4853 } else if (!dump_opt['q']) {
4854 print_l2arc_header();
4856 (void) printf(" magic: %llu\n",
4857 (u_longlong_t)l2dhdr.dh_magic);
4858 (void) printf(" version: %llu\n",
4859 (u_longlong_t)l2dhdr.dh_version);
4860 (void) printf(" pool_guid: %llu\n",
4861 (u_longlong_t)l2dhdr.dh_spa_guid);
4862 (void) printf(" flags: %llu\n",
4863 (u_longlong_t)l2dhdr.dh_flags);
4864 (void) printf(" start_lbps[0]: %llu\n",
4865 (u_longlong_t)
4866 l2dhdr.dh_start_lbps[0].lbp_daddr);
4867 (void) printf(" start_lbps[1]: %llu\n",
4868 (u_longlong_t)
4869 l2dhdr.dh_start_lbps[1].lbp_daddr);
4870 (void) printf(" log_blk_ent: %llu\n",
4871 (u_longlong_t)l2dhdr.dh_log_entries);
4872 (void) printf(" start: %llu\n",
4873 (u_longlong_t)l2dhdr.dh_start);
4874 (void) printf(" end: %llu\n",
4875 (u_longlong_t)l2dhdr.dh_end);
4876 (void) printf(" evict: %llu\n",
4877 (u_longlong_t)l2dhdr.dh_evict);
4878 (void) printf(" lb_asize_refcount: %llu\n",
4879 (u_longlong_t)l2dhdr.dh_lb_asize);
4880 (void) printf(" lb_count_refcount: %llu\n",
4881 (u_longlong_t)l2dhdr.dh_lb_count);
4882 (void) printf(" trim_action_time: %llu\n",
4883 (u_longlong_t)l2dhdr.dh_trim_action_time);
4884 (void) printf(" trim_state: %llu\n\n",
4885 (u_longlong_t)l2dhdr.dh_trim_state);
4888 dump_l2arc_log_blocks(fd, &l2dhdr, &rebuild);
4890 * The total aligned size of log blocks and the number of log blocks
4891 * reported in the header of the device may be less than what zdb
4892 * reports by dump_l2arc_log_blocks() which emulates l2arc_rebuild().
4893 * This happens because dump_l2arc_log_blocks() lacks the memory
4894 * pressure valve that l2arc_rebuild() has. Thus, if we are on a system
4895 * with low memory, l2arc_rebuild will exit prematurely and dh_lb_asize
4896 * and dh_lb_count will be lower to begin with than what exists on the
4897 * device. This is normal and zdb should not exit with an error. The
4898 * opposite case should never happen though, the values reported in the
4899 * header should never be higher than what dump_l2arc_log_blocks() and
4900 * l2arc_rebuild() report. If this happens there is a leak in the
4901 * accounting of log blocks.
4903 if (l2dhdr.dh_lb_asize > rebuild.dh_lb_asize ||
4904 l2dhdr.dh_lb_count > rebuild.dh_lb_count)
4905 return (1);
4907 return (0);
4910 static void
4911 dump_config_from_label(zdb_label_t *label, size_t buflen, int l)
4913 if (dump_opt['q'])
4914 return;
4916 if ((dump_opt['l'] < 3) && (first_label(label->config) != l))
4917 return;
4919 print_label_header(label, l);
4920 dump_nvlist(label->config_nv, 4);
4921 print_label_numbers(" labels = ", label->config);
4923 if (dump_opt['l'] >= 2)
4924 dump_nvlist_stats(label->config_nv, buflen);
4927 #define ZDB_MAX_UB_HEADER_SIZE 32
4929 static void
4930 dump_label_uberblocks(zdb_label_t *label, uint64_t ashift, int label_num)
4933 vdev_t vd;
4934 char header[ZDB_MAX_UB_HEADER_SIZE];
4936 vd.vdev_ashift = ashift;
4937 vd.vdev_top = &vd;
4939 for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
4940 uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
4941 uberblock_t *ub = (void *)((char *)&label->label + uoff);
4942 cksum_record_t *rec = label->uberblocks[i];
4944 if (rec == NULL) {
4945 if (dump_opt['u'] >= 2) {
4946 print_label_header(label, label_num);
4947 (void) printf(" Uberblock[%d] invalid\n", i);
4949 continue;
4952 if ((dump_opt['u'] < 3) && (first_label(rec) != label_num))
4953 continue;
4955 if ((dump_opt['u'] < 4) &&
4956 (ub->ub_mmp_magic == MMP_MAGIC) && ub->ub_mmp_delay &&
4957 (i >= VDEV_UBERBLOCK_COUNT(&vd) - MMP_BLOCKS_PER_LABEL))
4958 continue;
4960 print_label_header(label, label_num);
4961 (void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
4962 " Uberblock[%d]\n", i);
4963 dump_uberblock(ub, header, "");
4964 print_label_numbers(" labels = ", rec);
4968 static char curpath[PATH_MAX];
4971 * Iterate through the path components, recursively passing
4972 * current one's obj and remaining path until we find the obj
4973 * for the last one.
4975 static int
4976 dump_path_impl(objset_t *os, uint64_t obj, char *name, uint64_t *retobj)
4978 int err;
4979 boolean_t header = B_TRUE;
4980 uint64_t child_obj;
4981 char *s;
4982 dmu_buf_t *db;
4983 dmu_object_info_t doi;
4985 if ((s = strchr(name, '/')) != NULL)
4986 *s = '\0';
4987 err = zap_lookup(os, obj, name, 8, 1, &child_obj);
4989 (void) strlcat(curpath, name, sizeof (curpath));
4991 if (err != 0) {
4992 (void) fprintf(stderr, "failed to lookup %s: %s\n",
4993 curpath, strerror(err));
4994 return (err);
4997 child_obj = ZFS_DIRENT_OBJ(child_obj);
4998 err = sa_buf_hold(os, child_obj, FTAG, &db);
4999 if (err != 0) {
5000 (void) fprintf(stderr,
5001 "failed to get SA dbuf for obj %llu: %s\n",
5002 (u_longlong_t)child_obj, strerror(err));
5003 return (EINVAL);
5005 dmu_object_info_from_db(db, &doi);
5006 sa_buf_rele(db, FTAG);
5008 if (doi.doi_bonus_type != DMU_OT_SA &&
5009 doi.doi_bonus_type != DMU_OT_ZNODE) {
5010 (void) fprintf(stderr, "invalid bonus type %d for obj %llu\n",
5011 doi.doi_bonus_type, (u_longlong_t)child_obj);
5012 return (EINVAL);
5015 if (dump_opt['v'] > 6) {
5016 (void) printf("obj=%llu %s type=%d bonustype=%d\n",
5017 (u_longlong_t)child_obj, curpath, doi.doi_type,
5018 doi.doi_bonus_type);
5021 (void) strlcat(curpath, "/", sizeof (curpath));
5023 switch (doi.doi_type) {
5024 case DMU_OT_DIRECTORY_CONTENTS:
5025 if (s != NULL && *(s + 1) != '\0')
5026 return (dump_path_impl(os, child_obj, s + 1, retobj));
5027 zfs_fallthrough;
5028 case DMU_OT_PLAIN_FILE_CONTENTS:
5029 if (retobj != NULL) {
5030 *retobj = child_obj;
5031 } else {
5032 dump_object(os, child_obj, dump_opt['v'], &header,
5033 NULL, 0);
5035 return (0);
5036 default:
5037 (void) fprintf(stderr, "object %llu has non-file/directory "
5038 "type %d\n", (u_longlong_t)obj, doi.doi_type);
5039 break;
5042 return (EINVAL);
5046 * Dump the blocks for the object specified by path inside the dataset.
5048 static int
5049 dump_path(char *ds, char *path, uint64_t *retobj)
5051 int err;
5052 objset_t *os;
5053 uint64_t root_obj;
5055 err = open_objset(ds, FTAG, &os);
5056 if (err != 0)
5057 return (err);
5059 err = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1, &root_obj);
5060 if (err != 0) {
5061 (void) fprintf(stderr, "can't lookup root znode: %s\n",
5062 strerror(err));
5063 close_objset(os, FTAG);
5064 return (EINVAL);
5067 (void) snprintf(curpath, sizeof (curpath), "dataset=%s path=/", ds);
5069 err = dump_path_impl(os, root_obj, path, retobj);
5071 close_objset(os, FTAG);
5072 return (err);
5075 static int
5076 dump_backup_bytes(objset_t *os, void *buf, int len, void *arg)
5078 const char *p = (const char *)buf;
5079 ssize_t nwritten;
5081 (void) os;
5082 (void) arg;
5084 /* Write the data out, handling short writes and signals. */
5085 while ((nwritten = write(STDOUT_FILENO, p, len)) < len) {
5086 if (nwritten < 0) {
5087 if (errno == EINTR)
5088 continue;
5089 return (errno);
5091 p += nwritten;
5092 len -= nwritten;
5095 return (0);
5098 static void
5099 dump_backup(const char *pool, uint64_t objset_id, const char *flagstr)
5101 boolean_t embed = B_FALSE;
5102 boolean_t large_block = B_FALSE;
5103 boolean_t compress = B_FALSE;
5104 boolean_t raw = B_FALSE;
5106 const char *c;
5107 for (c = flagstr; c != NULL && *c != '\0'; c++) {
5108 switch (*c) {
5109 case 'e':
5110 embed = B_TRUE;
5111 break;
5112 case 'L':
5113 large_block = B_TRUE;
5114 break;
5115 case 'c':
5116 compress = B_TRUE;
5117 break;
5118 case 'w':
5119 raw = B_TRUE;
5120 break;
5121 default:
5122 fprintf(stderr, "dump_backup: invalid flag "
5123 "'%c'\n", *c);
5124 return;
5128 if (isatty(STDOUT_FILENO)) {
5129 fprintf(stderr, "dump_backup: stream cannot be written "
5130 "to a terminal\n");
5131 return;
5134 offset_t off = 0;
5135 dmu_send_outparams_t out = {
5136 .dso_outfunc = dump_backup_bytes,
5137 .dso_dryrun = B_FALSE,
5140 int err = dmu_send_obj(pool, objset_id, /* fromsnap */0, embed,
5141 large_block, compress, raw, /* saved */ B_FALSE, STDOUT_FILENO,
5142 &off, &out);
5143 if (err != 0) {
5144 fprintf(stderr, "dump_backup: dmu_send_obj: %s\n",
5145 strerror(err));
5146 return;
5150 static int
5151 zdb_copy_object(objset_t *os, uint64_t srcobj, char *destfile)
5153 int err = 0;
5154 uint64_t size, readsize, oursize, offset;
5155 ssize_t writesize;
5156 sa_handle_t *hdl;
5158 (void) printf("Copying object %" PRIu64 " to file %s\n", srcobj,
5159 destfile);
5161 VERIFY3P(os, ==, sa_os);
5162 if ((err = sa_handle_get(os, srcobj, NULL, SA_HDL_PRIVATE, &hdl))) {
5163 (void) printf("Failed to get handle for SA znode\n");
5164 return (err);
5166 if ((err = sa_lookup(hdl, sa_attr_table[ZPL_SIZE], &size, 8))) {
5167 (void) sa_handle_destroy(hdl);
5168 return (err);
5170 (void) sa_handle_destroy(hdl);
5172 (void) printf("Object %" PRIu64 " is %" PRIu64 " bytes\n", srcobj,
5173 size);
5174 if (size == 0) {
5175 return (EINVAL);
5178 int fd = open(destfile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
5179 if (fd == -1)
5180 return (errno);
5182 * We cap the size at 1 mebibyte here to prevent
5183 * allocation failures and nigh-infinite printing if the
5184 * object is extremely large.
5186 oursize = MIN(size, 1 << 20);
5187 offset = 0;
5188 char *buf = kmem_alloc(oursize, KM_NOSLEEP);
5189 if (buf == NULL) {
5190 (void) close(fd);
5191 return (ENOMEM);
5194 while (offset < size) {
5195 readsize = MIN(size - offset, 1 << 20);
5196 err = dmu_read(os, srcobj, offset, readsize, buf, 0);
5197 if (err != 0) {
5198 (void) printf("got error %u from dmu_read\n", err);
5199 kmem_free(buf, oursize);
5200 (void) close(fd);
5201 return (err);
5203 if (dump_opt['v'] > 3) {
5204 (void) printf("Read offset=%" PRIu64 " size=%" PRIu64
5205 " error=%d\n", offset, readsize, err);
5208 writesize = write(fd, buf, readsize);
5209 if (writesize < 0) {
5210 err = errno;
5211 break;
5212 } else if (writesize != readsize) {
5213 /* Incomplete write */
5214 (void) fprintf(stderr, "Short write, only wrote %llu of"
5215 " %" PRIu64 " bytes, exiting...\n",
5216 (u_longlong_t)writesize, readsize);
5217 break;
5220 offset += readsize;
5223 (void) close(fd);
5225 if (buf != NULL)
5226 kmem_free(buf, oursize);
5228 return (err);
5231 static boolean_t
5232 label_cksum_valid(vdev_label_t *label, uint64_t offset)
5234 zio_checksum_info_t *ci = &zio_checksum_table[ZIO_CHECKSUM_LABEL];
5235 zio_cksum_t expected_cksum;
5236 zio_cksum_t actual_cksum;
5237 zio_cksum_t verifier;
5238 zio_eck_t *eck;
5239 int byteswap;
5241 void *data = (char *)label + offsetof(vdev_label_t, vl_vdev_phys);
5242 eck = (zio_eck_t *)((char *)(data) + VDEV_PHYS_SIZE) - 1;
5244 offset += offsetof(vdev_label_t, vl_vdev_phys);
5245 ZIO_SET_CHECKSUM(&verifier, offset, 0, 0, 0);
5247 byteswap = (eck->zec_magic == BSWAP_64(ZEC_MAGIC));
5248 if (byteswap)
5249 byteswap_uint64_array(&verifier, sizeof (zio_cksum_t));
5251 expected_cksum = eck->zec_cksum;
5252 eck->zec_cksum = verifier;
5254 abd_t *abd = abd_get_from_buf(data, VDEV_PHYS_SIZE);
5255 ci->ci_func[byteswap](abd, VDEV_PHYS_SIZE, NULL, &actual_cksum);
5256 abd_free(abd);
5258 if (byteswap)
5259 byteswap_uint64_array(&expected_cksum, sizeof (zio_cksum_t));
5261 if (ZIO_CHECKSUM_EQUAL(actual_cksum, expected_cksum))
5262 return (B_TRUE);
5264 return (B_FALSE);
5267 static int
5268 dump_label(const char *dev)
5270 char path[MAXPATHLEN];
5271 zdb_label_t labels[VDEV_LABELS] = {{{{0}}}};
5272 uint64_t psize, ashift, l2cache;
5273 struct stat64 statbuf;
5274 boolean_t config_found = B_FALSE;
5275 boolean_t error = B_FALSE;
5276 boolean_t read_l2arc_header = B_FALSE;
5277 avl_tree_t config_tree;
5278 avl_tree_t uberblock_tree;
5279 void *node, *cookie;
5280 int fd;
5283 * Check if we were given absolute path and use it as is.
5284 * Otherwise if the provided vdev name doesn't point to a file,
5285 * try prepending expected disk paths and partition numbers.
5287 (void) strlcpy(path, dev, sizeof (path));
5288 if (dev[0] != '/' && stat64(path, &statbuf) != 0) {
5289 int error;
5291 error = zfs_resolve_shortname(dev, path, MAXPATHLEN);
5292 if (error == 0 && zfs_dev_is_whole_disk(path)) {
5293 if (zfs_append_partition(path, MAXPATHLEN) == -1)
5294 error = ENOENT;
5297 if (error || (stat64(path, &statbuf) != 0)) {
5298 (void) printf("failed to find device %s, try "
5299 "specifying absolute path instead\n", dev);
5300 return (1);
5304 if ((fd = open64(path, O_RDONLY)) < 0) {
5305 (void) printf("cannot open '%s': %s\n", path, strerror(errno));
5306 zdb_exit(1);
5309 if (fstat64_blk(fd, &statbuf) != 0) {
5310 (void) printf("failed to stat '%s': %s\n", path,
5311 strerror(errno));
5312 (void) close(fd);
5313 zdb_exit(1);
5316 if (S_ISBLK(statbuf.st_mode) && zfs_dev_flush(fd) != 0)
5317 (void) printf("failed to invalidate cache '%s' : %s\n", path,
5318 strerror(errno));
5320 avl_create(&config_tree, cksum_record_compare,
5321 sizeof (cksum_record_t), offsetof(cksum_record_t, link));
5322 avl_create(&uberblock_tree, cksum_record_compare,
5323 sizeof (cksum_record_t), offsetof(cksum_record_t, link));
5325 psize = statbuf.st_size;
5326 psize = P2ALIGN_TYPED(psize, sizeof (vdev_label_t), uint64_t);
5327 ashift = SPA_MINBLOCKSHIFT;
5330 * 1. Read the label from disk
5331 * 2. Verify label cksum
5332 * 3. Unpack the configuration and insert in config tree.
5333 * 4. Traverse all uberblocks and insert in uberblock tree.
5335 for (int l = 0; l < VDEV_LABELS; l++) {
5336 zdb_label_t *label = &labels[l];
5337 char *buf = label->label.vl_vdev_phys.vp_nvlist;
5338 size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
5339 nvlist_t *config;
5340 cksum_record_t *rec;
5341 zio_cksum_t cksum;
5342 vdev_t vd;
5344 label->label_offset = vdev_label_offset(psize, l, 0);
5346 if (pread64(fd, &label->label, sizeof (label->label),
5347 label->label_offset) != sizeof (label->label)) {
5348 if (!dump_opt['q'])
5349 (void) printf("failed to read label %d\n", l);
5350 label->read_failed = B_TRUE;
5351 error = B_TRUE;
5352 continue;
5355 label->read_failed = B_FALSE;
5356 label->cksum_valid = label_cksum_valid(&label->label,
5357 label->label_offset);
5359 if (nvlist_unpack(buf, buflen, &config, 0) == 0) {
5360 nvlist_t *vdev_tree = NULL;
5361 size_t size;
5363 if ((nvlist_lookup_nvlist(config,
5364 ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
5365 (nvlist_lookup_uint64(vdev_tree,
5366 ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
5367 ashift = SPA_MINBLOCKSHIFT;
5369 if (nvlist_size(config, &size, NV_ENCODE_XDR) != 0)
5370 size = buflen;
5372 /* If the device is a cache device read the header. */
5373 if (!read_l2arc_header) {
5374 if (nvlist_lookup_uint64(config,
5375 ZPOOL_CONFIG_POOL_STATE, &l2cache) == 0 &&
5376 l2cache == POOL_STATE_L2CACHE) {
5377 read_l2arc_header = B_TRUE;
5381 fletcher_4_native_varsize(buf, size, &cksum);
5382 rec = cksum_record_insert(&config_tree, &cksum, l);
5384 label->config = rec;
5385 label->config_nv = config;
5386 config_found = B_TRUE;
5387 } else {
5388 error = B_TRUE;
5391 vd.vdev_ashift = ashift;
5392 vd.vdev_top = &vd;
5394 for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
5395 uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
5396 uberblock_t *ub = (void *)((char *)label + uoff);
5398 if (uberblock_verify(ub))
5399 continue;
5401 fletcher_4_native_varsize(ub, sizeof (*ub), &cksum);
5402 rec = cksum_record_insert(&uberblock_tree, &cksum, l);
5404 label->uberblocks[i] = rec;
5409 * Dump the label and uberblocks.
5411 for (int l = 0; l < VDEV_LABELS; l++) {
5412 zdb_label_t *label = &labels[l];
5413 size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
5415 if (label->read_failed == B_TRUE)
5416 continue;
5418 if (label->config_nv) {
5419 dump_config_from_label(label, buflen, l);
5420 } else {
5421 if (!dump_opt['q'])
5422 (void) printf("failed to unpack label %d\n", l);
5425 if (dump_opt['u'])
5426 dump_label_uberblocks(label, ashift, l);
5428 nvlist_free(label->config_nv);
5432 * Dump the L2ARC header, if existent.
5434 if (read_l2arc_header)
5435 error |= dump_l2arc_header(fd);
5437 cookie = NULL;
5438 while ((node = avl_destroy_nodes(&config_tree, &cookie)) != NULL)
5439 umem_free(node, sizeof (cksum_record_t));
5441 cookie = NULL;
5442 while ((node = avl_destroy_nodes(&uberblock_tree, &cookie)) != NULL)
5443 umem_free(node, sizeof (cksum_record_t));
5445 avl_destroy(&config_tree);
5446 avl_destroy(&uberblock_tree);
5448 (void) close(fd);
5450 return (config_found == B_FALSE ? 2 :
5451 (error == B_TRUE ? 1 : 0));
5454 static uint64_t dataset_feature_count[SPA_FEATURES];
5455 static uint64_t global_feature_count[SPA_FEATURES];
5456 static uint64_t remap_deadlist_count = 0;
5458 static int
5459 dump_one_objset(const char *dsname, void *arg)
5461 (void) arg;
5462 int error;
5463 objset_t *os;
5464 spa_feature_t f;
5466 error = open_objset(dsname, FTAG, &os);
5467 if (error != 0)
5468 return (0);
5470 for (f = 0; f < SPA_FEATURES; f++) {
5471 if (!dsl_dataset_feature_is_active(dmu_objset_ds(os), f))
5472 continue;
5473 ASSERT(spa_feature_table[f].fi_flags &
5474 ZFEATURE_FLAG_PER_DATASET);
5475 dataset_feature_count[f]++;
5478 if (dsl_dataset_remap_deadlist_exists(dmu_objset_ds(os))) {
5479 remap_deadlist_count++;
5482 for (dsl_bookmark_node_t *dbn =
5483 avl_first(&dmu_objset_ds(os)->ds_bookmarks); dbn != NULL;
5484 dbn = AVL_NEXT(&dmu_objset_ds(os)->ds_bookmarks, dbn)) {
5485 mos_obj_refd(dbn->dbn_phys.zbm_redaction_obj);
5486 if (dbn->dbn_phys.zbm_redaction_obj != 0) {
5487 global_feature_count[
5488 SPA_FEATURE_REDACTION_BOOKMARKS]++;
5489 objset_t *mos = os->os_spa->spa_meta_objset;
5490 dnode_t *rl;
5491 VERIFY0(dnode_hold(mos,
5492 dbn->dbn_phys.zbm_redaction_obj, FTAG, &rl));
5493 if (rl->dn_have_spill) {
5494 global_feature_count[
5495 SPA_FEATURE_REDACTION_LIST_SPILL]++;
5498 if (dbn->dbn_phys.zbm_flags & ZBM_FLAG_HAS_FBN)
5499 global_feature_count[SPA_FEATURE_BOOKMARK_WRITTEN]++;
5502 if (dsl_deadlist_is_open(&dmu_objset_ds(os)->ds_dir->dd_livelist) &&
5503 !dmu_objset_is_snapshot(os)) {
5504 global_feature_count[SPA_FEATURE_LIVELIST]++;
5507 dump_objset(os);
5508 close_objset(os, FTAG);
5509 fuid_table_destroy();
5510 return (0);
5514 * Block statistics.
5516 #define PSIZE_HISTO_SIZE (SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 2)
5517 typedef struct zdb_blkstats {
5518 uint64_t zb_asize;
5519 uint64_t zb_lsize;
5520 uint64_t zb_psize;
5521 uint64_t zb_count;
5522 uint64_t zb_gangs;
5523 uint64_t zb_ditto_samevdev;
5524 uint64_t zb_ditto_same_ms;
5525 uint64_t zb_psize_histogram[PSIZE_HISTO_SIZE];
5526 } zdb_blkstats_t;
5529 * Extended object types to report deferred frees and dedup auto-ditto blocks.
5531 #define ZDB_OT_DEFERRED (DMU_OT_NUMTYPES + 0)
5532 #define ZDB_OT_DITTO (DMU_OT_NUMTYPES + 1)
5533 #define ZDB_OT_OTHER (DMU_OT_NUMTYPES + 2)
5534 #define ZDB_OT_TOTAL (DMU_OT_NUMTYPES + 3)
5536 static const char *zdb_ot_extname[] = {
5537 "deferred free",
5538 "dedup ditto",
5539 "other",
5540 "Total",
5543 #define ZB_TOTAL DN_MAX_LEVELS
5544 #define SPA_MAX_FOR_16M (SPA_MAXBLOCKSHIFT+1)
5546 typedef struct zdb_brt_entry {
5547 dva_t zbre_dva;
5548 uint64_t zbre_refcount;
5549 avl_node_t zbre_node;
5550 } zdb_brt_entry_t;
5552 typedef struct zdb_cb {
5553 zdb_blkstats_t zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
5554 uint64_t zcb_removing_size;
5555 uint64_t zcb_checkpoint_size;
5556 uint64_t zcb_dedup_asize;
5557 uint64_t zcb_dedup_blocks;
5558 uint64_t zcb_clone_asize;
5559 uint64_t zcb_clone_blocks;
5560 uint64_t zcb_psize_count[SPA_MAX_FOR_16M];
5561 uint64_t zcb_lsize_count[SPA_MAX_FOR_16M];
5562 uint64_t zcb_asize_count[SPA_MAX_FOR_16M];
5563 uint64_t zcb_psize_len[SPA_MAX_FOR_16M];
5564 uint64_t zcb_lsize_len[SPA_MAX_FOR_16M];
5565 uint64_t zcb_asize_len[SPA_MAX_FOR_16M];
5566 uint64_t zcb_psize_total;
5567 uint64_t zcb_lsize_total;
5568 uint64_t zcb_asize_total;
5569 uint64_t zcb_embedded_blocks[NUM_BP_EMBEDDED_TYPES];
5570 uint64_t zcb_embedded_histogram[NUM_BP_EMBEDDED_TYPES]
5571 [BPE_PAYLOAD_SIZE + 1];
5572 uint64_t zcb_start;
5573 hrtime_t zcb_lastprint;
5574 uint64_t zcb_totalasize;
5575 uint64_t zcb_errors[256];
5576 int zcb_readfails;
5577 int zcb_haderrors;
5578 spa_t *zcb_spa;
5579 uint32_t **zcb_vd_obsolete_counts;
5580 avl_tree_t zcb_brt;
5581 boolean_t zcb_brt_is_active;
5582 } zdb_cb_t;
5584 /* test if two DVA offsets from same vdev are within the same metaslab */
5585 static boolean_t
5586 same_metaslab(spa_t *spa, uint64_t vdev, uint64_t off1, uint64_t off2)
5588 vdev_t *vd = vdev_lookup_top(spa, vdev);
5589 uint64_t ms_shift = vd->vdev_ms_shift;
5591 return ((off1 >> ms_shift) == (off2 >> ms_shift));
5595 * Used to simplify reporting of the histogram data.
5597 typedef struct one_histo {
5598 const char *name;
5599 uint64_t *count;
5600 uint64_t *len;
5601 uint64_t cumulative;
5602 } one_histo_t;
5605 * The number of separate histograms processed for psize, lsize and asize.
5607 #define NUM_HISTO 3
5610 * This routine will create a fixed column size output of three different
5611 * histograms showing by blocksize of 512 - 2^ SPA_MAX_FOR_16M
5612 * the count, length and cumulative length of the psize, lsize and
5613 * asize blocks.
5615 * All three types of blocks are listed on a single line
5617 * By default the table is printed in nicenumber format (e.g. 123K) but
5618 * if the '-P' parameter is specified then the full raw number (parseable)
5619 * is printed out.
5621 static void
5622 dump_size_histograms(zdb_cb_t *zcb)
5625 * A temporary buffer that allows us to convert a number into
5626 * a string using zdb_nicenumber to allow either raw or human
5627 * readable numbers to be output.
5629 char numbuf[32];
5632 * Define titles which are used in the headers of the tables
5633 * printed by this routine.
5635 const char blocksize_title1[] = "block";
5636 const char blocksize_title2[] = "size";
5637 const char count_title[] = "Count";
5638 const char length_title[] = "Size";
5639 const char cumulative_title[] = "Cum.";
5642 * Setup the histogram arrays (psize, lsize, and asize).
5644 one_histo_t parm_histo[NUM_HISTO];
5646 parm_histo[0].name = "psize";
5647 parm_histo[0].count = zcb->zcb_psize_count;
5648 parm_histo[0].len = zcb->zcb_psize_len;
5649 parm_histo[0].cumulative = 0;
5651 parm_histo[1].name = "lsize";
5652 parm_histo[1].count = zcb->zcb_lsize_count;
5653 parm_histo[1].len = zcb->zcb_lsize_len;
5654 parm_histo[1].cumulative = 0;
5656 parm_histo[2].name = "asize";
5657 parm_histo[2].count = zcb->zcb_asize_count;
5658 parm_histo[2].len = zcb->zcb_asize_len;
5659 parm_histo[2].cumulative = 0;
5662 (void) printf("\nBlock Size Histogram\n");
5664 * Print the first line titles
5666 if (dump_opt['P'])
5667 (void) printf("\n%s\t", blocksize_title1);
5668 else
5669 (void) printf("\n%7s ", blocksize_title1);
5671 for (int j = 0; j < NUM_HISTO; j++) {
5672 if (dump_opt['P']) {
5673 if (j < NUM_HISTO - 1) {
5674 (void) printf("%s\t\t\t", parm_histo[j].name);
5675 } else {
5676 /* Don't print trailing spaces */
5677 (void) printf(" %s", parm_histo[j].name);
5679 } else {
5680 if (j < NUM_HISTO - 1) {
5681 /* Left aligned strings in the output */
5682 (void) printf("%-7s ",
5683 parm_histo[j].name);
5684 } else {
5685 /* Don't print trailing spaces */
5686 (void) printf("%s", parm_histo[j].name);
5690 (void) printf("\n");
5693 * Print the second line titles
5695 if (dump_opt['P']) {
5696 (void) printf("%s\t", blocksize_title2);
5697 } else {
5698 (void) printf("%7s ", blocksize_title2);
5701 for (int i = 0; i < NUM_HISTO; i++) {
5702 if (dump_opt['P']) {
5703 (void) printf("%s\t%s\t%s\t",
5704 count_title, length_title, cumulative_title);
5705 } else {
5706 (void) printf("%7s%7s%7s",
5707 count_title, length_title, cumulative_title);
5710 (void) printf("\n");
5713 * Print the rows
5715 for (int i = SPA_MINBLOCKSHIFT; i < SPA_MAX_FOR_16M; i++) {
5718 * Print the first column showing the blocksize
5720 zdb_nicenum((1ULL << i), numbuf, sizeof (numbuf));
5722 if (dump_opt['P']) {
5723 printf("%s", numbuf);
5724 } else {
5725 printf("%7s:", numbuf);
5729 * Print the remaining set of 3 columns per size:
5730 * for psize, lsize and asize
5732 for (int j = 0; j < NUM_HISTO; j++) {
5733 parm_histo[j].cumulative += parm_histo[j].len[i];
5735 zdb_nicenum(parm_histo[j].count[i],
5736 numbuf, sizeof (numbuf));
5737 if (dump_opt['P'])
5738 (void) printf("\t%s", numbuf);
5739 else
5740 (void) printf("%7s", numbuf);
5742 zdb_nicenum(parm_histo[j].len[i],
5743 numbuf, sizeof (numbuf));
5744 if (dump_opt['P'])
5745 (void) printf("\t%s", numbuf);
5746 else
5747 (void) printf("%7s", numbuf);
5749 zdb_nicenum(parm_histo[j].cumulative,
5750 numbuf, sizeof (numbuf));
5751 if (dump_opt['P'])
5752 (void) printf("\t%s", numbuf);
5753 else
5754 (void) printf("%7s", numbuf);
5756 (void) printf("\n");
5760 static void
5761 zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
5762 dmu_object_type_t type)
5764 int i;
5766 ASSERT(type < ZDB_OT_TOTAL);
5768 if (zilog && zil_bp_tree_add(zilog, bp) != 0)
5769 return;
5772 * This flag controls if we will issue a claim for the block while
5773 * counting it, to ensure that all blocks are referenced in space maps.
5774 * We don't issue claims if we're not doing leak tracking, because it's
5775 * expensive if the user isn't interested. We also don't claim the
5776 * second or later occurences of cloned or dedup'd blocks, because we
5777 * already claimed them the first time.
5779 boolean_t do_claim = !dump_opt['L'];
5781 spa_config_enter(zcb->zcb_spa, SCL_CONFIG, FTAG, RW_READER);
5783 blkptr_t tempbp;
5784 if (BP_GET_DEDUP(bp)) {
5786 * Dedup'd blocks are special. We need to count them, so we can
5787 * later uncount them when reporting leaked space, and we must
5788 * only claim them once.
5790 * We use the existing dedup system to track what we've seen.
5791 * The first time we see a block, we do a ddt_lookup() to see
5792 * if it exists in the DDT. If we're doing leak tracking, we
5793 * claim the block at this time.
5795 * Each time we see a block, we reduce the refcount in the
5796 * entry by one, and add to the size and count of dedup'd
5797 * blocks to report at the end.
5800 ddt_t *ddt = ddt_select(zcb->zcb_spa, bp);
5802 ddt_enter(ddt);
5805 * Find the block. This will create the entry in memory, but
5806 * we'll know if that happened by its refcount.
5808 ddt_entry_t *dde = ddt_lookup(ddt, bp);
5811 * ddt_lookup() can return NULL if this block didn't exist
5812 * in the DDT and creating it would take the DDT over its
5813 * quota. Since we got the block from disk, it must exist in
5814 * the DDT, so this can't happen. However, when unique entries
5815 * are pruned, the dedup bit can be set with no corresponding
5816 * entry in the DDT.
5818 if (dde == NULL) {
5819 ddt_exit(ddt);
5820 goto skipped;
5823 /* Get the phys for this variant */
5824 ddt_phys_variant_t v = ddt_phys_select(ddt, dde, bp);
5827 * This entry may have multiple sets of DVAs. We must claim
5828 * each set the first time we see them in a real block on disk,
5829 * or count them on subsequent occurences. We don't have a
5830 * convenient way to track the first time we see each variant,
5831 * so we repurpose dde_io as a set of "seen" flag bits. We can
5832 * do this safely in zdb because it never writes, so it will
5833 * never have a writing zio for this block in that pointer.
5835 boolean_t seen = !!(((uintptr_t)dde->dde_io) & (1 << v));
5836 if (!seen)
5837 dde->dde_io =
5838 (void *)(((uintptr_t)dde->dde_io) | (1 << v));
5840 /* Consume a reference for this block. */
5841 if (ddt_phys_total_refcnt(ddt, dde->dde_phys) > 0)
5842 ddt_phys_decref(dde->dde_phys, v);
5845 * If this entry has a single flat phys, it may have been
5846 * extended with additional DVAs at some time in its life.
5847 * This block might be from before it was fully extended, and
5848 * so have fewer DVAs.
5850 * If this is the first time we've seen this block, and we
5851 * claimed it as-is, then we would miss the claim on some
5852 * number of DVAs, which would then be seen as leaked.
5854 * In all cases, if we've had fewer DVAs, then the asize would
5855 * be too small, and would lead to the pool apparently using
5856 * more space than allocated.
5858 * To handle this, we copy the canonical set of DVAs from the
5859 * entry back to the block pointer before we claim it.
5861 if (v == DDT_PHYS_FLAT) {
5862 ASSERT3U(BP_GET_BIRTH(bp), ==,
5863 ddt_phys_birth(dde->dde_phys, v));
5864 tempbp = *bp;
5865 ddt_bp_fill(dde->dde_phys, v, &tempbp,
5866 BP_GET_BIRTH(bp));
5867 bp = &tempbp;
5870 if (seen) {
5872 * The second or later time we see this block,
5873 * it's a duplicate and we count it.
5875 zcb->zcb_dedup_asize += BP_GET_ASIZE(bp);
5876 zcb->zcb_dedup_blocks++;
5878 /* Already claimed, don't do it again. */
5879 do_claim = B_FALSE;
5882 ddt_exit(ddt);
5883 } else if (zcb->zcb_brt_is_active &&
5884 brt_maybe_exists(zcb->zcb_spa, bp)) {
5886 * Cloned blocks are special. We need to count them, so we can
5887 * later uncount them when reporting leaked space, and we must
5888 * only claim them once.
5890 * To do this, we keep our own in-memory BRT. For each block
5891 * we haven't seen before, we look it up in the real BRT and
5892 * if its there, we note it and its refcount then proceed as
5893 * normal. If we see the block again, we count it as a clone
5894 * and then give it no further consideration.
5896 zdb_brt_entry_t zbre_search, *zbre;
5897 avl_index_t where;
5899 zbre_search.zbre_dva = bp->blk_dva[0];
5900 zbre = avl_find(&zcb->zcb_brt, &zbre_search, &where);
5901 if (zbre == NULL) {
5902 /* Not seen before; track it */
5903 uint64_t refcnt =
5904 brt_entry_get_refcount(zcb->zcb_spa, bp);
5905 if (refcnt > 0) {
5906 zbre = umem_zalloc(sizeof (zdb_brt_entry_t),
5907 UMEM_NOFAIL);
5908 zbre->zbre_dva = bp->blk_dva[0];
5909 zbre->zbre_refcount = refcnt;
5910 avl_insert(&zcb->zcb_brt, zbre, where);
5912 } else {
5914 * Second or later occurrence, count it and take a
5915 * refcount.
5917 zcb->zcb_clone_asize += BP_GET_ASIZE(bp);
5918 zcb->zcb_clone_blocks++;
5920 zbre->zbre_refcount--;
5921 if (zbre->zbre_refcount == 0) {
5922 avl_remove(&zcb->zcb_brt, zbre);
5923 umem_free(zbre, sizeof (zdb_brt_entry_t));
5926 /* Already claimed, don't do it again. */
5927 do_claim = B_FALSE;
5931 skipped:
5932 for (i = 0; i < 4; i++) {
5933 int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
5934 int t = (i & 1) ? type : ZDB_OT_TOTAL;
5935 int equal;
5936 zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
5938 zb->zb_asize += BP_GET_ASIZE(bp);
5939 zb->zb_lsize += BP_GET_LSIZE(bp);
5940 zb->zb_psize += BP_GET_PSIZE(bp);
5941 zb->zb_count++;
5944 * The histogram is only big enough to record blocks up to
5945 * SPA_OLD_MAXBLOCKSIZE; larger blocks go into the last,
5946 * "other", bucket.
5948 unsigned idx = BP_GET_PSIZE(bp) >> SPA_MINBLOCKSHIFT;
5949 idx = MIN(idx, SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 1);
5950 zb->zb_psize_histogram[idx]++;
5952 zb->zb_gangs += BP_COUNT_GANG(bp);
5954 switch (BP_GET_NDVAS(bp)) {
5955 case 2:
5956 if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5957 DVA_GET_VDEV(&bp->blk_dva[1])) {
5958 zb->zb_ditto_samevdev++;
5960 if (same_metaslab(zcb->zcb_spa,
5961 DVA_GET_VDEV(&bp->blk_dva[0]),
5962 DVA_GET_OFFSET(&bp->blk_dva[0]),
5963 DVA_GET_OFFSET(&bp->blk_dva[1])))
5964 zb->zb_ditto_same_ms++;
5966 break;
5967 case 3:
5968 equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5969 DVA_GET_VDEV(&bp->blk_dva[1])) +
5970 (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5971 DVA_GET_VDEV(&bp->blk_dva[2])) +
5972 (DVA_GET_VDEV(&bp->blk_dva[1]) ==
5973 DVA_GET_VDEV(&bp->blk_dva[2]));
5974 if (equal != 0) {
5975 zb->zb_ditto_samevdev++;
5977 if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5978 DVA_GET_VDEV(&bp->blk_dva[1]) &&
5979 same_metaslab(zcb->zcb_spa,
5980 DVA_GET_VDEV(&bp->blk_dva[0]),
5981 DVA_GET_OFFSET(&bp->blk_dva[0]),
5982 DVA_GET_OFFSET(&bp->blk_dva[1])))
5983 zb->zb_ditto_same_ms++;
5984 else if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5985 DVA_GET_VDEV(&bp->blk_dva[2]) &&
5986 same_metaslab(zcb->zcb_spa,
5987 DVA_GET_VDEV(&bp->blk_dva[0]),
5988 DVA_GET_OFFSET(&bp->blk_dva[0]),
5989 DVA_GET_OFFSET(&bp->blk_dva[2])))
5990 zb->zb_ditto_same_ms++;
5991 else if (DVA_GET_VDEV(&bp->blk_dva[1]) ==
5992 DVA_GET_VDEV(&bp->blk_dva[2]) &&
5993 same_metaslab(zcb->zcb_spa,
5994 DVA_GET_VDEV(&bp->blk_dva[1]),
5995 DVA_GET_OFFSET(&bp->blk_dva[1]),
5996 DVA_GET_OFFSET(&bp->blk_dva[2])))
5997 zb->zb_ditto_same_ms++;
5999 break;
6003 spa_config_exit(zcb->zcb_spa, SCL_CONFIG, FTAG);
6005 if (BP_IS_EMBEDDED(bp)) {
6006 zcb->zcb_embedded_blocks[BPE_GET_ETYPE(bp)]++;
6007 zcb->zcb_embedded_histogram[BPE_GET_ETYPE(bp)]
6008 [BPE_GET_PSIZE(bp)]++;
6009 return;
6012 * The binning histogram bins by powers of two up to
6013 * SPA_MAXBLOCKSIZE rather than creating bins for
6014 * every possible blocksize found in the pool.
6016 int bin = highbit64(BP_GET_PSIZE(bp)) - 1;
6018 zcb->zcb_psize_count[bin]++;
6019 zcb->zcb_psize_len[bin] += BP_GET_PSIZE(bp);
6020 zcb->zcb_psize_total += BP_GET_PSIZE(bp);
6022 bin = highbit64(BP_GET_LSIZE(bp)) - 1;
6024 zcb->zcb_lsize_count[bin]++;
6025 zcb->zcb_lsize_len[bin] += BP_GET_LSIZE(bp);
6026 zcb->zcb_lsize_total += BP_GET_LSIZE(bp);
6028 bin = highbit64(BP_GET_ASIZE(bp)) - 1;
6030 zcb->zcb_asize_count[bin]++;
6031 zcb->zcb_asize_len[bin] += BP_GET_ASIZE(bp);
6032 zcb->zcb_asize_total += BP_GET_ASIZE(bp);
6034 if (!do_claim)
6035 return;
6037 VERIFY0(zio_wait(zio_claim(NULL, zcb->zcb_spa,
6038 spa_min_claim_txg(zcb->zcb_spa), bp, NULL, NULL,
6039 ZIO_FLAG_CANFAIL)));
6042 static void
6043 zdb_blkptr_done(zio_t *zio)
6045 spa_t *spa = zio->io_spa;
6046 blkptr_t *bp = zio->io_bp;
6047 int ioerr = zio->io_error;
6048 zdb_cb_t *zcb = zio->io_private;
6049 zbookmark_phys_t *zb = &zio->io_bookmark;
6051 mutex_enter(&spa->spa_scrub_lock);
6052 spa->spa_load_verify_bytes -= BP_GET_PSIZE(bp);
6053 cv_broadcast(&spa->spa_scrub_io_cv);
6055 if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
6056 char blkbuf[BP_SPRINTF_LEN];
6058 zcb->zcb_haderrors = 1;
6059 zcb->zcb_errors[ioerr]++;
6061 if (dump_opt['b'] >= 2)
6062 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
6063 else
6064 blkbuf[0] = '\0';
6066 (void) printf("zdb_blkptr_cb: "
6067 "Got error %d reading "
6068 "<%llu, %llu, %lld, %llx> %s -- skipping\n",
6069 ioerr,
6070 (u_longlong_t)zb->zb_objset,
6071 (u_longlong_t)zb->zb_object,
6072 (u_longlong_t)zb->zb_level,
6073 (u_longlong_t)zb->zb_blkid,
6074 blkbuf);
6076 mutex_exit(&spa->spa_scrub_lock);
6078 abd_free(zio->io_abd);
6081 static int
6082 zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
6083 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
6085 zdb_cb_t *zcb = arg;
6086 dmu_object_type_t type;
6087 boolean_t is_metadata;
6089 if (zb->zb_level == ZB_DNODE_LEVEL)
6090 return (0);
6092 if (dump_opt['b'] >= 5 && BP_GET_LOGICAL_BIRTH(bp) > 0) {
6093 char blkbuf[BP_SPRINTF_LEN];
6094 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
6095 (void) printf("objset %llu object %llu "
6096 "level %lld offset 0x%llx %s\n",
6097 (u_longlong_t)zb->zb_objset,
6098 (u_longlong_t)zb->zb_object,
6099 (longlong_t)zb->zb_level,
6100 (u_longlong_t)blkid2offset(dnp, bp, zb),
6101 blkbuf);
6104 if (BP_IS_HOLE(bp) || BP_IS_REDACTED(bp))
6105 return (0);
6107 type = BP_GET_TYPE(bp);
6109 zdb_count_block(zcb, zilog, bp,
6110 (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
6112 is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
6114 if (!BP_IS_EMBEDDED(bp) &&
6115 (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata))) {
6116 size_t size = BP_GET_PSIZE(bp);
6117 abd_t *abd = abd_alloc(size, B_FALSE);
6118 int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
6120 /* If it's an intent log block, failure is expected. */
6121 if (zb->zb_level == ZB_ZIL_LEVEL)
6122 flags |= ZIO_FLAG_SPECULATIVE;
6124 mutex_enter(&spa->spa_scrub_lock);
6125 while (spa->spa_load_verify_bytes > max_inflight_bytes)
6126 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
6127 spa->spa_load_verify_bytes += size;
6128 mutex_exit(&spa->spa_scrub_lock);
6130 zio_nowait(zio_read(NULL, spa, bp, abd, size,
6131 zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
6134 zcb->zcb_readfails = 0;
6136 /* only call gethrtime() every 100 blocks */
6137 static int iters;
6138 if (++iters > 100)
6139 iters = 0;
6140 else
6141 return (0);
6143 if (dump_opt['b'] < 5 && gethrtime() > zcb->zcb_lastprint + NANOSEC) {
6144 uint64_t now = gethrtime();
6145 char buf[10];
6146 uint64_t bytes = zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL].zb_asize;
6147 uint64_t kb_per_sec =
6148 1 + bytes / (1 + ((now - zcb->zcb_start) / 1000 / 1000));
6149 uint64_t sec_remaining =
6150 (zcb->zcb_totalasize - bytes) / 1024 / kb_per_sec;
6152 /* make sure nicenum has enough space */
6153 _Static_assert(sizeof (buf) >= NN_NUMBUF_SZ, "buf truncated");
6155 zfs_nicebytes(bytes, buf, sizeof (buf));
6156 (void) fprintf(stderr,
6157 "\r%5s completed (%4"PRIu64"MB/s) "
6158 "estimated time remaining: "
6159 "%"PRIu64"hr %02"PRIu64"min %02"PRIu64"sec ",
6160 buf, kb_per_sec / 1024,
6161 sec_remaining / 60 / 60,
6162 sec_remaining / 60 % 60,
6163 sec_remaining % 60);
6165 zcb->zcb_lastprint = now;
6168 return (0);
6171 static void
6172 zdb_leak(void *arg, uint64_t start, uint64_t size)
6174 vdev_t *vd = arg;
6176 (void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
6177 (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
6180 static metaslab_ops_t zdb_metaslab_ops = {
6181 NULL /* alloc */
6184 static int
6185 load_unflushed_svr_segs_cb(spa_t *spa, space_map_entry_t *sme,
6186 uint64_t txg, void *arg)
6188 spa_vdev_removal_t *svr = arg;
6190 uint64_t offset = sme->sme_offset;
6191 uint64_t size = sme->sme_run;
6193 /* skip vdevs we don't care about */
6194 if (sme->sme_vdev != svr->svr_vdev_id)
6195 return (0);
6197 vdev_t *vd = vdev_lookup_top(spa, sme->sme_vdev);
6198 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
6199 ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
6201 if (txg < metaslab_unflushed_txg(ms))
6202 return (0);
6204 if (sme->sme_type == SM_ALLOC)
6205 range_tree_add(svr->svr_allocd_segs, offset, size);
6206 else
6207 range_tree_remove(svr->svr_allocd_segs, offset, size);
6209 return (0);
6212 static void
6213 claim_segment_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
6214 uint64_t size, void *arg)
6216 (void) inner_offset, (void) arg;
6219 * This callback was called through a remap from
6220 * a device being removed. Therefore, the vdev that
6221 * this callback is applied to is a concrete
6222 * vdev.
6224 ASSERT(vdev_is_concrete(vd));
6226 VERIFY0(metaslab_claim_impl(vd, offset, size,
6227 spa_min_claim_txg(vd->vdev_spa)));
6230 static void
6231 claim_segment_cb(void *arg, uint64_t offset, uint64_t size)
6233 vdev_t *vd = arg;
6235 vdev_indirect_ops.vdev_op_remap(vd, offset, size,
6236 claim_segment_impl_cb, NULL);
6240 * After accounting for all allocated blocks that are directly referenced,
6241 * we might have missed a reference to a block from a partially complete
6242 * (and thus unused) indirect mapping object. We perform a secondary pass
6243 * through the metaslabs we have already mapped and claim the destination
6244 * blocks.
6246 static void
6247 zdb_claim_removing(spa_t *spa, zdb_cb_t *zcb)
6249 if (dump_opt['L'])
6250 return;
6252 if (spa->spa_vdev_removal == NULL)
6253 return;
6255 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6257 spa_vdev_removal_t *svr = spa->spa_vdev_removal;
6258 vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
6259 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6261 ASSERT0(range_tree_space(svr->svr_allocd_segs));
6263 range_tree_t *allocs = range_tree_create(NULL, RANGE_SEG64, NULL, 0, 0);
6264 for (uint64_t msi = 0; msi < vd->vdev_ms_count; msi++) {
6265 metaslab_t *msp = vd->vdev_ms[msi];
6267 ASSERT0(range_tree_space(allocs));
6268 if (msp->ms_sm != NULL)
6269 VERIFY0(space_map_load(msp->ms_sm, allocs, SM_ALLOC));
6270 range_tree_vacate(allocs, range_tree_add, svr->svr_allocd_segs);
6272 range_tree_destroy(allocs);
6274 iterate_through_spacemap_logs(spa, load_unflushed_svr_segs_cb, svr);
6277 * Clear everything past what has been synced,
6278 * because we have not allocated mappings for
6279 * it yet.
6281 range_tree_clear(svr->svr_allocd_segs,
6282 vdev_indirect_mapping_max_offset(vim),
6283 vd->vdev_asize - vdev_indirect_mapping_max_offset(vim));
6285 zcb->zcb_removing_size += range_tree_space(svr->svr_allocd_segs);
6286 range_tree_vacate(svr->svr_allocd_segs, claim_segment_cb, vd);
6288 spa_config_exit(spa, SCL_CONFIG, FTAG);
6291 static int
6292 increment_indirect_mapping_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
6293 dmu_tx_t *tx)
6295 (void) tx;
6296 zdb_cb_t *zcb = arg;
6297 spa_t *spa = zcb->zcb_spa;
6298 vdev_t *vd;
6299 const dva_t *dva = &bp->blk_dva[0];
6301 ASSERT(!bp_freed);
6302 ASSERT(!dump_opt['L']);
6303 ASSERT3U(BP_GET_NDVAS(bp), ==, 1);
6305 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
6306 vd = vdev_lookup_top(zcb->zcb_spa, DVA_GET_VDEV(dva));
6307 ASSERT3P(vd, !=, NULL);
6308 spa_config_exit(spa, SCL_VDEV, FTAG);
6310 ASSERT(vd->vdev_indirect_config.vic_mapping_object != 0);
6311 ASSERT3P(zcb->zcb_vd_obsolete_counts[vd->vdev_id], !=, NULL);
6313 vdev_indirect_mapping_increment_obsolete_count(
6314 vd->vdev_indirect_mapping,
6315 DVA_GET_OFFSET(dva), DVA_GET_ASIZE(dva),
6316 zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
6318 return (0);
6321 static uint32_t *
6322 zdb_load_obsolete_counts(vdev_t *vd)
6324 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6325 spa_t *spa = vd->vdev_spa;
6326 spa_condensing_indirect_phys_t *scip =
6327 &spa->spa_condensing_indirect_phys;
6328 uint64_t obsolete_sm_object;
6329 uint32_t *counts;
6331 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
6332 EQUIV(obsolete_sm_object != 0, vd->vdev_obsolete_sm != NULL);
6333 counts = vdev_indirect_mapping_load_obsolete_counts(vim);
6334 if (vd->vdev_obsolete_sm != NULL) {
6335 vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
6336 vd->vdev_obsolete_sm);
6338 if (scip->scip_vdev == vd->vdev_id &&
6339 scip->scip_prev_obsolete_sm_object != 0) {
6340 space_map_t *prev_obsolete_sm = NULL;
6341 VERIFY0(space_map_open(&prev_obsolete_sm, spa->spa_meta_objset,
6342 scip->scip_prev_obsolete_sm_object, 0, vd->vdev_asize, 0));
6343 vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
6344 prev_obsolete_sm);
6345 space_map_close(prev_obsolete_sm);
6347 return (counts);
6350 typedef struct checkpoint_sm_exclude_entry_arg {
6351 vdev_t *cseea_vd;
6352 uint64_t cseea_checkpoint_size;
6353 } checkpoint_sm_exclude_entry_arg_t;
6355 static int
6356 checkpoint_sm_exclude_entry_cb(space_map_entry_t *sme, void *arg)
6358 checkpoint_sm_exclude_entry_arg_t *cseea = arg;
6359 vdev_t *vd = cseea->cseea_vd;
6360 metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
6361 uint64_t end = sme->sme_offset + sme->sme_run;
6363 ASSERT(sme->sme_type == SM_FREE);
6366 * Since the vdev_checkpoint_sm exists in the vdev level
6367 * and the ms_sm space maps exist in the metaslab level,
6368 * an entry in the checkpoint space map could theoretically
6369 * cross the boundaries of the metaslab that it belongs.
6371 * In reality, because of the way that we populate and
6372 * manipulate the checkpoint's space maps currently,
6373 * there shouldn't be any entries that cross metaslabs.
6374 * Hence the assertion below.
6376 * That said, there is no fundamental requirement that
6377 * the checkpoint's space map entries should not cross
6378 * metaslab boundaries. So if needed we could add code
6379 * that handles metaslab-crossing segments in the future.
6381 VERIFY3U(sme->sme_offset, >=, ms->ms_start);
6382 VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
6385 * By removing the entry from the allocated segments we
6386 * also verify that the entry is there to begin with.
6388 mutex_enter(&ms->ms_lock);
6389 range_tree_remove(ms->ms_allocatable, sme->sme_offset, sme->sme_run);
6390 mutex_exit(&ms->ms_lock);
6392 cseea->cseea_checkpoint_size += sme->sme_run;
6393 return (0);
6396 static void
6397 zdb_leak_init_vdev_exclude_checkpoint(vdev_t *vd, zdb_cb_t *zcb)
6399 spa_t *spa = vd->vdev_spa;
6400 space_map_t *checkpoint_sm = NULL;
6401 uint64_t checkpoint_sm_obj;
6404 * If there is no vdev_top_zap, we are in a pool whose
6405 * version predates the pool checkpoint feature.
6407 if (vd->vdev_top_zap == 0)
6408 return;
6411 * If there is no reference of the vdev_checkpoint_sm in
6412 * the vdev_top_zap, then one of the following scenarios
6413 * is true:
6415 * 1] There is no checkpoint
6416 * 2] There is a checkpoint, but no checkpointed blocks
6417 * have been freed yet
6418 * 3] The current vdev is indirect
6420 * In these cases we return immediately.
6422 if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
6423 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
6424 return;
6426 VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
6427 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1,
6428 &checkpoint_sm_obj));
6430 checkpoint_sm_exclude_entry_arg_t cseea;
6431 cseea.cseea_vd = vd;
6432 cseea.cseea_checkpoint_size = 0;
6434 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
6435 checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
6437 VERIFY0(space_map_iterate(checkpoint_sm,
6438 space_map_length(checkpoint_sm),
6439 checkpoint_sm_exclude_entry_cb, &cseea));
6440 space_map_close(checkpoint_sm);
6442 zcb->zcb_checkpoint_size += cseea.cseea_checkpoint_size;
6445 static void
6446 zdb_leak_init_exclude_checkpoint(spa_t *spa, zdb_cb_t *zcb)
6448 ASSERT(!dump_opt['L']);
6450 vdev_t *rvd = spa->spa_root_vdev;
6451 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
6452 ASSERT3U(c, ==, rvd->vdev_child[c]->vdev_id);
6453 zdb_leak_init_vdev_exclude_checkpoint(rvd->vdev_child[c], zcb);
6457 static int
6458 count_unflushed_space_cb(spa_t *spa, space_map_entry_t *sme,
6459 uint64_t txg, void *arg)
6461 int64_t *ualloc_space = arg;
6463 uint64_t offset = sme->sme_offset;
6464 uint64_t vdev_id = sme->sme_vdev;
6466 vdev_t *vd = vdev_lookup_top(spa, vdev_id);
6467 if (!vdev_is_concrete(vd))
6468 return (0);
6470 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
6471 ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
6473 if (txg < metaslab_unflushed_txg(ms))
6474 return (0);
6476 if (sme->sme_type == SM_ALLOC)
6477 *ualloc_space += sme->sme_run;
6478 else
6479 *ualloc_space -= sme->sme_run;
6481 return (0);
6484 static int64_t
6485 get_unflushed_alloc_space(spa_t *spa)
6487 if (dump_opt['L'])
6488 return (0);
6490 int64_t ualloc_space = 0;
6491 iterate_through_spacemap_logs(spa, count_unflushed_space_cb,
6492 &ualloc_space);
6493 return (ualloc_space);
6496 static int
6497 load_unflushed_cb(spa_t *spa, space_map_entry_t *sme, uint64_t txg, void *arg)
6499 maptype_t *uic_maptype = arg;
6501 uint64_t offset = sme->sme_offset;
6502 uint64_t size = sme->sme_run;
6503 uint64_t vdev_id = sme->sme_vdev;
6505 vdev_t *vd = vdev_lookup_top(spa, vdev_id);
6507 /* skip indirect vdevs */
6508 if (!vdev_is_concrete(vd))
6509 return (0);
6511 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
6513 ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
6514 ASSERT(*uic_maptype == SM_ALLOC || *uic_maptype == SM_FREE);
6516 if (txg < metaslab_unflushed_txg(ms))
6517 return (0);
6519 if (*uic_maptype == sme->sme_type)
6520 range_tree_add(ms->ms_allocatable, offset, size);
6521 else
6522 range_tree_remove(ms->ms_allocatable, offset, size);
6524 return (0);
6527 static void
6528 load_unflushed_to_ms_allocatables(spa_t *spa, maptype_t maptype)
6530 iterate_through_spacemap_logs(spa, load_unflushed_cb, &maptype);
6533 static void
6534 load_concrete_ms_allocatable_trees(spa_t *spa, maptype_t maptype)
6536 vdev_t *rvd = spa->spa_root_vdev;
6537 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
6538 vdev_t *vd = rvd->vdev_child[i];
6540 ASSERT3U(i, ==, vd->vdev_id);
6542 if (vd->vdev_ops == &vdev_indirect_ops)
6543 continue;
6545 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
6546 metaslab_t *msp = vd->vdev_ms[m];
6548 (void) fprintf(stderr,
6549 "\rloading concrete vdev %llu, "
6550 "metaslab %llu of %llu ...",
6551 (longlong_t)vd->vdev_id,
6552 (longlong_t)msp->ms_id,
6553 (longlong_t)vd->vdev_ms_count);
6555 mutex_enter(&msp->ms_lock);
6556 range_tree_vacate(msp->ms_allocatable, NULL, NULL);
6559 * We don't want to spend the CPU manipulating the
6560 * size-ordered tree, so clear the range_tree ops.
6562 msp->ms_allocatable->rt_ops = NULL;
6564 if (msp->ms_sm != NULL) {
6565 VERIFY0(space_map_load(msp->ms_sm,
6566 msp->ms_allocatable, maptype));
6568 if (!msp->ms_loaded)
6569 msp->ms_loaded = B_TRUE;
6570 mutex_exit(&msp->ms_lock);
6574 load_unflushed_to_ms_allocatables(spa, maptype);
6578 * vm_idxp is an in-out parameter which (for indirect vdevs) is the
6579 * index in vim_entries that has the first entry in this metaslab.
6580 * On return, it will be set to the first entry after this metaslab.
6582 static void
6583 load_indirect_ms_allocatable_tree(vdev_t *vd, metaslab_t *msp,
6584 uint64_t *vim_idxp)
6586 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6588 mutex_enter(&msp->ms_lock);
6589 range_tree_vacate(msp->ms_allocatable, NULL, NULL);
6592 * We don't want to spend the CPU manipulating the
6593 * size-ordered tree, so clear the range_tree ops.
6595 msp->ms_allocatable->rt_ops = NULL;
6597 for (; *vim_idxp < vdev_indirect_mapping_num_entries(vim);
6598 (*vim_idxp)++) {
6599 vdev_indirect_mapping_entry_phys_t *vimep =
6600 &vim->vim_entries[*vim_idxp];
6601 uint64_t ent_offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
6602 uint64_t ent_len = DVA_GET_ASIZE(&vimep->vimep_dst);
6603 ASSERT3U(ent_offset, >=, msp->ms_start);
6604 if (ent_offset >= msp->ms_start + msp->ms_size)
6605 break;
6608 * Mappings do not cross metaslab boundaries,
6609 * because we create them by walking the metaslabs.
6611 ASSERT3U(ent_offset + ent_len, <=,
6612 msp->ms_start + msp->ms_size);
6613 range_tree_add(msp->ms_allocatable, ent_offset, ent_len);
6616 if (!msp->ms_loaded)
6617 msp->ms_loaded = B_TRUE;
6618 mutex_exit(&msp->ms_lock);
6621 static void
6622 zdb_leak_init_prepare_indirect_vdevs(spa_t *spa, zdb_cb_t *zcb)
6624 ASSERT(!dump_opt['L']);
6626 vdev_t *rvd = spa->spa_root_vdev;
6627 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
6628 vdev_t *vd = rvd->vdev_child[c];
6630 ASSERT3U(c, ==, vd->vdev_id);
6632 if (vd->vdev_ops != &vdev_indirect_ops)
6633 continue;
6636 * Note: we don't check for mapping leaks on
6637 * removing vdevs because their ms_allocatable's
6638 * are used to look for leaks in allocated space.
6640 zcb->zcb_vd_obsolete_counts[c] = zdb_load_obsolete_counts(vd);
6643 * Normally, indirect vdevs don't have any
6644 * metaslabs. We want to set them up for
6645 * zio_claim().
6647 vdev_metaslab_group_create(vd);
6648 VERIFY0(vdev_metaslab_init(vd, 0));
6650 vdev_indirect_mapping_t *vim __maybe_unused =
6651 vd->vdev_indirect_mapping;
6652 uint64_t vim_idx = 0;
6653 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
6655 (void) fprintf(stderr,
6656 "\rloading indirect vdev %llu, "
6657 "metaslab %llu of %llu ...",
6658 (longlong_t)vd->vdev_id,
6659 (longlong_t)vd->vdev_ms[m]->ms_id,
6660 (longlong_t)vd->vdev_ms_count);
6662 load_indirect_ms_allocatable_tree(vd, vd->vdev_ms[m],
6663 &vim_idx);
6665 ASSERT3U(vim_idx, ==, vdev_indirect_mapping_num_entries(vim));
6669 static void
6670 zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
6672 zcb->zcb_spa = spa;
6674 if (dump_opt['L'])
6675 return;
6677 dsl_pool_t *dp = spa->spa_dsl_pool;
6678 vdev_t *rvd = spa->spa_root_vdev;
6681 * We are going to be changing the meaning of the metaslab's
6682 * ms_allocatable. Ensure that the allocator doesn't try to
6683 * use the tree.
6685 spa->spa_normal_class->mc_ops = &zdb_metaslab_ops;
6686 spa->spa_log_class->mc_ops = &zdb_metaslab_ops;
6687 spa->spa_embedded_log_class->mc_ops = &zdb_metaslab_ops;
6689 zcb->zcb_vd_obsolete_counts =
6690 umem_zalloc(rvd->vdev_children * sizeof (uint32_t *),
6691 UMEM_NOFAIL);
6694 * For leak detection, we overload the ms_allocatable trees
6695 * to contain allocated segments instead of free segments.
6696 * As a result, we can't use the normal metaslab_load/unload
6697 * interfaces.
6699 zdb_leak_init_prepare_indirect_vdevs(spa, zcb);
6700 load_concrete_ms_allocatable_trees(spa, SM_ALLOC);
6703 * On load_concrete_ms_allocatable_trees() we loaded all the
6704 * allocated entries from the ms_sm to the ms_allocatable for
6705 * each metaslab. If the pool has a checkpoint or is in the
6706 * middle of discarding a checkpoint, some of these blocks
6707 * may have been freed but their ms_sm may not have been
6708 * updated because they are referenced by the checkpoint. In
6709 * order to avoid false-positives during leak-detection, we
6710 * go through the vdev's checkpoint space map and exclude all
6711 * its entries from their relevant ms_allocatable.
6713 * We also aggregate the space held by the checkpoint and add
6714 * it to zcb_checkpoint_size.
6716 * Note that at this point we are also verifying that all the
6717 * entries on the checkpoint_sm are marked as allocated in
6718 * the ms_sm of their relevant metaslab.
6719 * [see comment in checkpoint_sm_exclude_entry_cb()]
6721 zdb_leak_init_exclude_checkpoint(spa, zcb);
6722 ASSERT3U(zcb->zcb_checkpoint_size, ==, spa_get_checkpoint_space(spa));
6724 /* for cleaner progress output */
6725 (void) fprintf(stderr, "\n");
6727 if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
6728 ASSERT(spa_feature_is_enabled(spa,
6729 SPA_FEATURE_DEVICE_REMOVAL));
6730 (void) bpobj_iterate_nofree(&dp->dp_obsolete_bpobj,
6731 increment_indirect_mapping_cb, zcb, NULL);
6735 static boolean_t
6736 zdb_check_for_obsolete_leaks(vdev_t *vd, zdb_cb_t *zcb)
6738 boolean_t leaks = B_FALSE;
6739 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6740 uint64_t total_leaked = 0;
6741 boolean_t are_precise = B_FALSE;
6743 ASSERT(vim != NULL);
6745 for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
6746 vdev_indirect_mapping_entry_phys_t *vimep =
6747 &vim->vim_entries[i];
6748 uint64_t obsolete_bytes = 0;
6749 uint64_t offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
6750 metaslab_t *msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
6753 * This is not very efficient but it's easy to
6754 * verify correctness.
6756 for (uint64_t inner_offset = 0;
6757 inner_offset < DVA_GET_ASIZE(&vimep->vimep_dst);
6758 inner_offset += 1ULL << vd->vdev_ashift) {
6759 if (range_tree_contains(msp->ms_allocatable,
6760 offset + inner_offset, 1ULL << vd->vdev_ashift)) {
6761 obsolete_bytes += 1ULL << vd->vdev_ashift;
6765 int64_t bytes_leaked = obsolete_bytes -
6766 zcb->zcb_vd_obsolete_counts[vd->vdev_id][i];
6767 ASSERT3U(DVA_GET_ASIZE(&vimep->vimep_dst), >=,
6768 zcb->zcb_vd_obsolete_counts[vd->vdev_id][i]);
6770 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
6771 if (bytes_leaked != 0 && (are_precise || dump_opt['d'] >= 5)) {
6772 (void) printf("obsolete indirect mapping count "
6773 "mismatch on %llu:%llx:%llx : %llx bytes leaked\n",
6774 (u_longlong_t)vd->vdev_id,
6775 (u_longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
6776 (u_longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
6777 (u_longlong_t)bytes_leaked);
6779 total_leaked += ABS(bytes_leaked);
6782 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
6783 if (!are_precise && total_leaked > 0) {
6784 int pct_leaked = total_leaked * 100 /
6785 vdev_indirect_mapping_bytes_mapped(vim);
6786 (void) printf("cannot verify obsolete indirect mapping "
6787 "counts of vdev %llu because precise feature was not "
6788 "enabled when it was removed: %d%% (%llx bytes) of mapping"
6789 "unreferenced\n",
6790 (u_longlong_t)vd->vdev_id, pct_leaked,
6791 (u_longlong_t)total_leaked);
6792 } else if (total_leaked > 0) {
6793 (void) printf("obsolete indirect mapping count mismatch "
6794 "for vdev %llu -- %llx total bytes mismatched\n",
6795 (u_longlong_t)vd->vdev_id,
6796 (u_longlong_t)total_leaked);
6797 leaks |= B_TRUE;
6800 vdev_indirect_mapping_free_obsolete_counts(vim,
6801 zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
6802 zcb->zcb_vd_obsolete_counts[vd->vdev_id] = NULL;
6804 return (leaks);
6807 static boolean_t
6808 zdb_leak_fini(spa_t *spa, zdb_cb_t *zcb)
6810 if (dump_opt['L'])
6811 return (B_FALSE);
6813 boolean_t leaks = B_FALSE;
6814 vdev_t *rvd = spa->spa_root_vdev;
6815 for (unsigned c = 0; c < rvd->vdev_children; c++) {
6816 vdev_t *vd = rvd->vdev_child[c];
6818 if (zcb->zcb_vd_obsolete_counts[c] != NULL) {
6819 leaks |= zdb_check_for_obsolete_leaks(vd, zcb);
6822 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
6823 metaslab_t *msp = vd->vdev_ms[m];
6824 ASSERT3P(msp->ms_group, ==, (msp->ms_group->mg_class ==
6825 spa_embedded_log_class(spa)) ?
6826 vd->vdev_log_mg : vd->vdev_mg);
6829 * ms_allocatable has been overloaded
6830 * to contain allocated segments. Now that
6831 * we finished traversing all blocks, any
6832 * block that remains in the ms_allocatable
6833 * represents an allocated block that we
6834 * did not claim during the traversal.
6835 * Claimed blocks would have been removed
6836 * from the ms_allocatable. For indirect
6837 * vdevs, space remaining in the tree
6838 * represents parts of the mapping that are
6839 * not referenced, which is not a bug.
6841 if (vd->vdev_ops == &vdev_indirect_ops) {
6842 range_tree_vacate(msp->ms_allocatable,
6843 NULL, NULL);
6844 } else {
6845 range_tree_vacate(msp->ms_allocatable,
6846 zdb_leak, vd);
6848 if (msp->ms_loaded) {
6849 msp->ms_loaded = B_FALSE;
6854 umem_free(zcb->zcb_vd_obsolete_counts,
6855 rvd->vdev_children * sizeof (uint32_t *));
6856 zcb->zcb_vd_obsolete_counts = NULL;
6858 return (leaks);
6861 static int
6862 count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
6864 (void) tx;
6865 zdb_cb_t *zcb = arg;
6867 if (dump_opt['b'] >= 5) {
6868 char blkbuf[BP_SPRINTF_LEN];
6869 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
6870 (void) printf("[%s] %s\n",
6871 "deferred free", blkbuf);
6873 zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
6874 return (0);
6878 * Iterate over livelists which have been destroyed by the user but
6879 * are still present in the MOS, waiting to be freed
6881 static void
6882 iterate_deleted_livelists(spa_t *spa, ll_iter_t func, void *arg)
6884 objset_t *mos = spa->spa_meta_objset;
6885 uint64_t zap_obj;
6886 int err = zap_lookup(mos, DMU_POOL_DIRECTORY_OBJECT,
6887 DMU_POOL_DELETED_CLONES, sizeof (uint64_t), 1, &zap_obj);
6888 if (err == ENOENT)
6889 return;
6890 ASSERT0(err);
6892 zap_cursor_t zc;
6893 zap_attribute_t *attrp = zap_attribute_alloc();
6894 dsl_deadlist_t ll;
6895 /* NULL out os prior to dsl_deadlist_open in case it's garbage */
6896 ll.dl_os = NULL;
6897 for (zap_cursor_init(&zc, mos, zap_obj);
6898 zap_cursor_retrieve(&zc, attrp) == 0;
6899 (void) zap_cursor_advance(&zc)) {
6900 dsl_deadlist_open(&ll, mos, attrp->za_first_integer);
6901 func(&ll, arg);
6902 dsl_deadlist_close(&ll);
6904 zap_cursor_fini(&zc);
6905 zap_attribute_free(attrp);
6908 static int
6909 bpobj_count_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
6910 dmu_tx_t *tx)
6912 ASSERT(!bp_freed);
6913 return (count_block_cb(arg, bp, tx));
6916 static int
6917 livelist_entry_count_blocks_cb(void *args, dsl_deadlist_entry_t *dle)
6919 zdb_cb_t *zbc = args;
6920 bplist_t blks;
6921 bplist_create(&blks);
6922 /* determine which blocks have been alloc'd but not freed */
6923 VERIFY0(dsl_process_sub_livelist(&dle->dle_bpobj, &blks, NULL, NULL));
6924 /* count those blocks */
6925 (void) bplist_iterate(&blks, count_block_cb, zbc, NULL);
6926 bplist_destroy(&blks);
6927 return (0);
6930 static void
6931 livelist_count_blocks(dsl_deadlist_t *ll, void *arg)
6933 dsl_deadlist_iterate(ll, livelist_entry_count_blocks_cb, arg);
6937 * Count the blocks in the livelists that have been destroyed by the user
6938 * but haven't yet been freed.
6940 static void
6941 deleted_livelists_count_blocks(spa_t *spa, zdb_cb_t *zbc)
6943 iterate_deleted_livelists(spa, livelist_count_blocks, zbc);
6946 static void
6947 dump_livelist_cb(dsl_deadlist_t *ll, void *arg)
6949 ASSERT3P(arg, ==, NULL);
6950 global_feature_count[SPA_FEATURE_LIVELIST]++;
6951 dump_blkptr_list(ll, "Deleted Livelist");
6952 dsl_deadlist_iterate(ll, sublivelist_verify_lightweight, NULL);
6956 * Print out, register object references to, and increment feature counts for
6957 * livelists that have been destroyed by the user but haven't yet been freed.
6959 static void
6960 deleted_livelists_dump_mos(spa_t *spa)
6962 uint64_t zap_obj;
6963 objset_t *mos = spa->spa_meta_objset;
6964 int err = zap_lookup(mos, DMU_POOL_DIRECTORY_OBJECT,
6965 DMU_POOL_DELETED_CLONES, sizeof (uint64_t), 1, &zap_obj);
6966 if (err == ENOENT)
6967 return;
6968 mos_obj_refd(zap_obj);
6969 iterate_deleted_livelists(spa, dump_livelist_cb, NULL);
6972 static int
6973 zdb_brt_entry_compare(const void *zcn1, const void *zcn2)
6975 const dva_t *dva1 = &((const zdb_brt_entry_t *)zcn1)->zbre_dva;
6976 const dva_t *dva2 = &((const zdb_brt_entry_t *)zcn2)->zbre_dva;
6977 int cmp;
6979 cmp = TREE_CMP(DVA_GET_VDEV(dva1), DVA_GET_VDEV(dva2));
6980 if (cmp == 0)
6981 cmp = TREE_CMP(DVA_GET_OFFSET(dva1), DVA_GET_OFFSET(dva2));
6983 return (cmp);
6986 static int
6987 dump_block_stats(spa_t *spa)
6989 zdb_cb_t *zcb;
6990 zdb_blkstats_t *zb, *tzb;
6991 uint64_t norm_alloc, norm_space, total_alloc, total_found;
6992 int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
6993 TRAVERSE_NO_DECRYPT | TRAVERSE_HARD;
6994 boolean_t leaks = B_FALSE;
6995 int e, c, err;
6996 bp_embedded_type_t i;
6998 ddt_prefetch_all(spa);
7000 zcb = umem_zalloc(sizeof (zdb_cb_t), UMEM_NOFAIL);
7002 if (spa_feature_is_active(spa, SPA_FEATURE_BLOCK_CLONING)) {
7003 avl_create(&zcb->zcb_brt, zdb_brt_entry_compare,
7004 sizeof (zdb_brt_entry_t),
7005 offsetof(zdb_brt_entry_t, zbre_node));
7006 zcb->zcb_brt_is_active = B_TRUE;
7009 (void) printf("\nTraversing all blocks %s%s%s%s%s...\n\n",
7010 (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
7011 (dump_opt['c'] == 1) ? "metadata " : "",
7012 dump_opt['c'] ? "checksums " : "",
7013 (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
7014 !dump_opt['L'] ? "nothing leaked " : "");
7017 * When leak detection is enabled we load all space maps as SM_ALLOC
7018 * maps, then traverse the pool claiming each block we discover. If
7019 * the pool is perfectly consistent, the segment trees will be empty
7020 * when we're done. Anything left over is a leak; any block we can't
7021 * claim (because it's not part of any space map) is a double
7022 * allocation, reference to a freed block, or an unclaimed log block.
7024 * When leak detection is disabled (-L option) we still traverse the
7025 * pool claiming each block we discover, but we skip opening any space
7026 * maps.
7028 zdb_leak_init(spa, zcb);
7031 * If there's a deferred-free bplist, process that first.
7033 (void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
7034 bpobj_count_block_cb, zcb, NULL);
7036 if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
7037 (void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
7038 bpobj_count_block_cb, zcb, NULL);
7041 zdb_claim_removing(spa, zcb);
7043 if (spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
7044 VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
7045 spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
7046 zcb, NULL));
7049 deleted_livelists_count_blocks(spa, zcb);
7051 if (dump_opt['c'] > 1)
7052 flags |= TRAVERSE_PREFETCH_DATA;
7054 zcb->zcb_totalasize = metaslab_class_get_alloc(spa_normal_class(spa));
7055 zcb->zcb_totalasize += metaslab_class_get_alloc(spa_special_class(spa));
7056 zcb->zcb_totalasize += metaslab_class_get_alloc(spa_dedup_class(spa));
7057 zcb->zcb_totalasize +=
7058 metaslab_class_get_alloc(spa_embedded_log_class(spa));
7059 zcb->zcb_start = zcb->zcb_lastprint = gethrtime();
7060 err = traverse_pool(spa, 0, flags, zdb_blkptr_cb, zcb);
7063 * If we've traversed the data blocks then we need to wait for those
7064 * I/Os to complete. We leverage "The Godfather" zio to wait on
7065 * all async I/Os to complete.
7067 if (dump_opt['c']) {
7068 for (c = 0; c < max_ncpus; c++) {
7069 (void) zio_wait(spa->spa_async_zio_root[c]);
7070 spa->spa_async_zio_root[c] = zio_root(spa, NULL, NULL,
7071 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
7072 ZIO_FLAG_GODFATHER);
7075 ASSERT0(spa->spa_load_verify_bytes);
7078 * Done after zio_wait() since zcb_haderrors is modified in
7079 * zdb_blkptr_done()
7081 zcb->zcb_haderrors |= err;
7083 if (zcb->zcb_haderrors) {
7084 (void) printf("\nError counts:\n\n");
7085 (void) printf("\t%5s %s\n", "errno", "count");
7086 for (e = 0; e < 256; e++) {
7087 if (zcb->zcb_errors[e] != 0) {
7088 (void) printf("\t%5d %llu\n",
7089 e, (u_longlong_t)zcb->zcb_errors[e]);
7095 * Report any leaked segments.
7097 leaks |= zdb_leak_fini(spa, zcb);
7099 tzb = &zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
7101 norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
7102 norm_space = metaslab_class_get_space(spa_normal_class(spa));
7104 total_alloc = norm_alloc +
7105 metaslab_class_get_alloc(spa_log_class(spa)) +
7106 metaslab_class_get_alloc(spa_embedded_log_class(spa)) +
7107 metaslab_class_get_alloc(spa_special_class(spa)) +
7108 metaslab_class_get_alloc(spa_dedup_class(spa)) +
7109 get_unflushed_alloc_space(spa);
7110 total_found =
7111 tzb->zb_asize - zcb->zcb_dedup_asize - zcb->zcb_clone_asize +
7112 zcb->zcb_removing_size + zcb->zcb_checkpoint_size;
7114 if (total_found == total_alloc && !dump_opt['L']) {
7115 (void) printf("\n\tNo leaks (block sum matches space"
7116 " maps exactly)\n");
7117 } else if (!dump_opt['L']) {
7118 (void) printf("block traversal size %llu != alloc %llu "
7119 "(%s %lld)\n",
7120 (u_longlong_t)total_found,
7121 (u_longlong_t)total_alloc,
7122 (dump_opt['L']) ? "unreachable" : "leaked",
7123 (longlong_t)(total_alloc - total_found));
7126 if (tzb->zb_count == 0) {
7127 umem_free(zcb, sizeof (zdb_cb_t));
7128 return (2);
7131 (void) printf("\n");
7132 (void) printf("\t%-16s %14llu\n", "bp count:",
7133 (u_longlong_t)tzb->zb_count);
7134 (void) printf("\t%-16s %14llu\n", "ganged count:",
7135 (longlong_t)tzb->zb_gangs);
7136 (void) printf("\t%-16s %14llu avg: %6llu\n", "bp logical:",
7137 (u_longlong_t)tzb->zb_lsize,
7138 (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
7139 (void) printf("\t%-16s %14llu avg: %6llu compression: %6.2f\n",
7140 "bp physical:", (u_longlong_t)tzb->zb_psize,
7141 (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
7142 (double)tzb->zb_lsize / tzb->zb_psize);
7143 (void) printf("\t%-16s %14llu avg: %6llu compression: %6.2f\n",
7144 "bp allocated:", (u_longlong_t)tzb->zb_asize,
7145 (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
7146 (double)tzb->zb_lsize / tzb->zb_asize);
7147 (void) printf("\t%-16s %14llu ref>1: %6llu deduplication: %6.2f\n",
7148 "bp deduped:", (u_longlong_t)zcb->zcb_dedup_asize,
7149 (u_longlong_t)zcb->zcb_dedup_blocks,
7150 (double)zcb->zcb_dedup_asize / tzb->zb_asize + 1.0);
7151 (void) printf("\t%-16s %14llu count: %6llu\n",
7152 "bp cloned:", (u_longlong_t)zcb->zcb_clone_asize,
7153 (u_longlong_t)zcb->zcb_clone_blocks);
7154 (void) printf("\t%-16s %14llu used: %5.2f%%\n", "Normal class:",
7155 (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
7157 if (spa_special_class(spa)->mc_allocator[0].mca_rotor != NULL) {
7158 uint64_t alloc = metaslab_class_get_alloc(
7159 spa_special_class(spa));
7160 uint64_t space = metaslab_class_get_space(
7161 spa_special_class(spa));
7163 (void) printf("\t%-16s %14llu used: %5.2f%%\n",
7164 "Special class", (u_longlong_t)alloc,
7165 100.0 * alloc / space);
7168 if (spa_dedup_class(spa)->mc_allocator[0].mca_rotor != NULL) {
7169 uint64_t alloc = metaslab_class_get_alloc(
7170 spa_dedup_class(spa));
7171 uint64_t space = metaslab_class_get_space(
7172 spa_dedup_class(spa));
7174 (void) printf("\t%-16s %14llu used: %5.2f%%\n",
7175 "Dedup class", (u_longlong_t)alloc,
7176 100.0 * alloc / space);
7179 if (spa_embedded_log_class(spa)->mc_allocator[0].mca_rotor != NULL) {
7180 uint64_t alloc = metaslab_class_get_alloc(
7181 spa_embedded_log_class(spa));
7182 uint64_t space = metaslab_class_get_space(
7183 spa_embedded_log_class(spa));
7185 (void) printf("\t%-16s %14llu used: %5.2f%%\n",
7186 "Embedded log class", (u_longlong_t)alloc,
7187 100.0 * alloc / space);
7190 for (i = 0; i < NUM_BP_EMBEDDED_TYPES; i++) {
7191 if (zcb->zcb_embedded_blocks[i] == 0)
7192 continue;
7193 (void) printf("\n");
7194 (void) printf("\tadditional, non-pointer bps of type %u: "
7195 "%10llu\n",
7196 i, (u_longlong_t)zcb->zcb_embedded_blocks[i]);
7198 if (dump_opt['b'] >= 3) {
7199 (void) printf("\t number of (compressed) bytes: "
7200 "number of bps\n");
7201 dump_histogram(zcb->zcb_embedded_histogram[i],
7202 sizeof (zcb->zcb_embedded_histogram[i]) /
7203 sizeof (zcb->zcb_embedded_histogram[i][0]), 0);
7207 if (tzb->zb_ditto_samevdev != 0) {
7208 (void) printf("\tDittoed blocks on same vdev: %llu\n",
7209 (longlong_t)tzb->zb_ditto_samevdev);
7211 if (tzb->zb_ditto_same_ms != 0) {
7212 (void) printf("\tDittoed blocks in same metaslab: %llu\n",
7213 (longlong_t)tzb->zb_ditto_same_ms);
7216 for (uint64_t v = 0; v < spa->spa_root_vdev->vdev_children; v++) {
7217 vdev_t *vd = spa->spa_root_vdev->vdev_child[v];
7218 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
7220 if (vim == NULL) {
7221 continue;
7224 char mem[32];
7225 zdb_nicenum(vdev_indirect_mapping_num_entries(vim),
7226 mem, vdev_indirect_mapping_size(vim));
7228 (void) printf("\tindirect vdev id %llu has %llu segments "
7229 "(%s in memory)\n",
7230 (longlong_t)vd->vdev_id,
7231 (longlong_t)vdev_indirect_mapping_num_entries(vim), mem);
7234 if (dump_opt['b'] >= 2) {
7235 int l, t, level;
7236 char csize[32], lsize[32], psize[32], asize[32];
7237 char avg[32], gang[32];
7238 (void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
7239 "\t avg\t comp\t%%Total\tType\n");
7241 zfs_blkstat_t *mdstats = umem_zalloc(sizeof (zfs_blkstat_t),
7242 UMEM_NOFAIL);
7244 for (t = 0; t <= ZDB_OT_TOTAL; t++) {
7245 const char *typename;
7247 /* make sure nicenum has enough space */
7248 _Static_assert(sizeof (csize) >= NN_NUMBUF_SZ,
7249 "csize truncated");
7250 _Static_assert(sizeof (lsize) >= NN_NUMBUF_SZ,
7251 "lsize truncated");
7252 _Static_assert(sizeof (psize) >= NN_NUMBUF_SZ,
7253 "psize truncated");
7254 _Static_assert(sizeof (asize) >= NN_NUMBUF_SZ,
7255 "asize truncated");
7256 _Static_assert(sizeof (avg) >= NN_NUMBUF_SZ,
7257 "avg truncated");
7258 _Static_assert(sizeof (gang) >= NN_NUMBUF_SZ,
7259 "gang truncated");
7261 if (t < DMU_OT_NUMTYPES)
7262 typename = dmu_ot[t].ot_name;
7263 else
7264 typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
7266 if (zcb->zcb_type[ZB_TOTAL][t].zb_asize == 0) {
7267 (void) printf("%6s\t%5s\t%5s\t%5s"
7268 "\t%5s\t%5s\t%6s\t%s\n",
7269 "-",
7270 "-",
7271 "-",
7272 "-",
7273 "-",
7274 "-",
7275 "-",
7276 typename);
7277 continue;
7280 for (l = ZB_TOTAL - 1; l >= -1; l--) {
7281 level = (l == -1 ? ZB_TOTAL : l);
7282 zb = &zcb->zcb_type[level][t];
7284 if (zb->zb_asize == 0)
7285 continue;
7287 if (level != ZB_TOTAL && t < DMU_OT_NUMTYPES &&
7288 (level > 0 || DMU_OT_IS_METADATA(t))) {
7289 mdstats->zb_count += zb->zb_count;
7290 mdstats->zb_lsize += zb->zb_lsize;
7291 mdstats->zb_psize += zb->zb_psize;
7292 mdstats->zb_asize += zb->zb_asize;
7293 mdstats->zb_gangs += zb->zb_gangs;
7296 if (dump_opt['b'] < 3 && level != ZB_TOTAL)
7297 continue;
7299 if (level == 0 && zb->zb_asize ==
7300 zcb->zcb_type[ZB_TOTAL][t].zb_asize)
7301 continue;
7303 zdb_nicenum(zb->zb_count, csize,
7304 sizeof (csize));
7305 zdb_nicenum(zb->zb_lsize, lsize,
7306 sizeof (lsize));
7307 zdb_nicenum(zb->zb_psize, psize,
7308 sizeof (psize));
7309 zdb_nicenum(zb->zb_asize, asize,
7310 sizeof (asize));
7311 zdb_nicenum(zb->zb_asize / zb->zb_count, avg,
7312 sizeof (avg));
7313 zdb_nicenum(zb->zb_gangs, gang, sizeof (gang));
7315 (void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
7316 "\t%5.2f\t%6.2f\t",
7317 csize, lsize, psize, asize, avg,
7318 (double)zb->zb_lsize / zb->zb_psize,
7319 100.0 * zb->zb_asize / tzb->zb_asize);
7321 if (level == ZB_TOTAL)
7322 (void) printf("%s\n", typename);
7323 else
7324 (void) printf(" L%d %s\n",
7325 level, typename);
7327 if (dump_opt['b'] >= 3 && zb->zb_gangs > 0) {
7328 (void) printf("\t number of ganged "
7329 "blocks: %s\n", gang);
7332 if (dump_opt['b'] >= 4) {
7333 (void) printf("psize "
7334 "(in 512-byte sectors): "
7335 "number of blocks\n");
7336 dump_histogram(zb->zb_psize_histogram,
7337 PSIZE_HISTO_SIZE, 0);
7341 zdb_nicenum(mdstats->zb_count, csize,
7342 sizeof (csize));
7343 zdb_nicenum(mdstats->zb_lsize, lsize,
7344 sizeof (lsize));
7345 zdb_nicenum(mdstats->zb_psize, psize,
7346 sizeof (psize));
7347 zdb_nicenum(mdstats->zb_asize, asize,
7348 sizeof (asize));
7349 zdb_nicenum(mdstats->zb_asize / mdstats->zb_count, avg,
7350 sizeof (avg));
7351 zdb_nicenum(mdstats->zb_gangs, gang, sizeof (gang));
7353 (void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
7354 "\t%5.2f\t%6.2f\t",
7355 csize, lsize, psize, asize, avg,
7356 (double)mdstats->zb_lsize / mdstats->zb_psize,
7357 100.0 * mdstats->zb_asize / tzb->zb_asize);
7358 (void) printf("%s\n", "Metadata Total");
7360 /* Output a table summarizing block sizes in the pool */
7361 if (dump_opt['b'] >= 2) {
7362 dump_size_histograms(zcb);
7365 umem_free(mdstats, sizeof (zfs_blkstat_t));
7368 (void) printf("\n");
7370 if (leaks) {
7371 umem_free(zcb, sizeof (zdb_cb_t));
7372 return (2);
7375 if (zcb->zcb_haderrors) {
7376 umem_free(zcb, sizeof (zdb_cb_t));
7377 return (3);
7380 umem_free(zcb, sizeof (zdb_cb_t));
7381 return (0);
7384 typedef struct zdb_ddt_entry {
7385 /* key must be first for ddt_key_compare */
7386 ddt_key_t zdde_key;
7387 uint64_t zdde_ref_blocks;
7388 uint64_t zdde_ref_lsize;
7389 uint64_t zdde_ref_psize;
7390 uint64_t zdde_ref_dsize;
7391 avl_node_t zdde_node;
7392 } zdb_ddt_entry_t;
7394 static int
7395 zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
7396 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
7398 (void) zilog, (void) dnp;
7399 avl_tree_t *t = arg;
7400 avl_index_t where;
7401 zdb_ddt_entry_t *zdde, zdde_search;
7403 if (zb->zb_level == ZB_DNODE_LEVEL || BP_IS_HOLE(bp) ||
7404 BP_IS_EMBEDDED(bp))
7405 return (0);
7407 if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
7408 (void) printf("traversing objset %llu, %llu objects, "
7409 "%lu blocks so far\n",
7410 (u_longlong_t)zb->zb_objset,
7411 (u_longlong_t)BP_GET_FILL(bp),
7412 avl_numnodes(t));
7415 if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
7416 BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
7417 return (0);
7419 ddt_key_fill(&zdde_search.zdde_key, bp);
7421 zdde = avl_find(t, &zdde_search, &where);
7423 if (zdde == NULL) {
7424 zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
7425 zdde->zdde_key = zdde_search.zdde_key;
7426 avl_insert(t, zdde, where);
7429 zdde->zdde_ref_blocks += 1;
7430 zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
7431 zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
7432 zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
7434 return (0);
7437 static void
7438 dump_simulated_ddt(spa_t *spa)
7440 avl_tree_t t;
7441 void *cookie = NULL;
7442 zdb_ddt_entry_t *zdde;
7443 ddt_histogram_t ddh_total = {{{0}}};
7444 ddt_stat_t dds_total = {0};
7446 avl_create(&t, ddt_key_compare,
7447 sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
7449 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7451 (void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
7452 TRAVERSE_NO_DECRYPT, zdb_ddt_add_cb, &t);
7454 spa_config_exit(spa, SCL_CONFIG, FTAG);
7456 while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
7457 uint64_t refcnt = zdde->zdde_ref_blocks;
7458 ASSERT(refcnt != 0);
7460 ddt_stat_t *dds = &ddh_total.ddh_stat[highbit64(refcnt) - 1];
7462 dds->dds_blocks += zdde->zdde_ref_blocks / refcnt;
7463 dds->dds_lsize += zdde->zdde_ref_lsize / refcnt;
7464 dds->dds_psize += zdde->zdde_ref_psize / refcnt;
7465 dds->dds_dsize += zdde->zdde_ref_dsize / refcnt;
7467 dds->dds_ref_blocks += zdde->zdde_ref_blocks;
7468 dds->dds_ref_lsize += zdde->zdde_ref_lsize;
7469 dds->dds_ref_psize += zdde->zdde_ref_psize;
7470 dds->dds_ref_dsize += zdde->zdde_ref_dsize;
7472 umem_free(zdde, sizeof (*zdde));
7475 avl_destroy(&t);
7477 ddt_histogram_total(&dds_total, &ddh_total);
7479 (void) printf("Simulated DDT histogram:\n");
7481 zpool_dump_ddt(&dds_total, &ddh_total);
7483 dump_dedup_ratio(&dds_total);
7486 static int
7487 verify_device_removal_feature_counts(spa_t *spa)
7489 uint64_t dr_feature_refcount = 0;
7490 uint64_t oc_feature_refcount = 0;
7491 uint64_t indirect_vdev_count = 0;
7492 uint64_t precise_vdev_count = 0;
7493 uint64_t obsolete_counts_object_count = 0;
7494 uint64_t obsolete_sm_count = 0;
7495 uint64_t obsolete_counts_count = 0;
7496 uint64_t scip_count = 0;
7497 uint64_t obsolete_bpobj_count = 0;
7498 int ret = 0;
7500 spa_condensing_indirect_phys_t *scip =
7501 &spa->spa_condensing_indirect_phys;
7502 if (scip->scip_next_mapping_object != 0) {
7503 vdev_t *vd = spa->spa_root_vdev->vdev_child[scip->scip_vdev];
7504 ASSERT(scip->scip_prev_obsolete_sm_object != 0);
7505 ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
7507 (void) printf("Condensing indirect vdev %llu: new mapping "
7508 "object %llu, prev obsolete sm %llu\n",
7509 (u_longlong_t)scip->scip_vdev,
7510 (u_longlong_t)scip->scip_next_mapping_object,
7511 (u_longlong_t)scip->scip_prev_obsolete_sm_object);
7512 if (scip->scip_prev_obsolete_sm_object != 0) {
7513 space_map_t *prev_obsolete_sm = NULL;
7514 VERIFY0(space_map_open(&prev_obsolete_sm,
7515 spa->spa_meta_objset,
7516 scip->scip_prev_obsolete_sm_object,
7517 0, vd->vdev_asize, 0));
7518 dump_spacemap(spa->spa_meta_objset, prev_obsolete_sm);
7519 (void) printf("\n");
7520 space_map_close(prev_obsolete_sm);
7523 scip_count += 2;
7526 for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
7527 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
7528 vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
7530 if (vic->vic_mapping_object != 0) {
7531 ASSERT(vd->vdev_ops == &vdev_indirect_ops ||
7532 vd->vdev_removing);
7533 indirect_vdev_count++;
7535 if (vd->vdev_indirect_mapping->vim_havecounts) {
7536 obsolete_counts_count++;
7540 boolean_t are_precise;
7541 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
7542 if (are_precise) {
7543 ASSERT(vic->vic_mapping_object != 0);
7544 precise_vdev_count++;
7547 uint64_t obsolete_sm_object;
7548 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
7549 if (obsolete_sm_object != 0) {
7550 ASSERT(vic->vic_mapping_object != 0);
7551 obsolete_sm_count++;
7555 (void) feature_get_refcount(spa,
7556 &spa_feature_table[SPA_FEATURE_DEVICE_REMOVAL],
7557 &dr_feature_refcount);
7558 (void) feature_get_refcount(spa,
7559 &spa_feature_table[SPA_FEATURE_OBSOLETE_COUNTS],
7560 &oc_feature_refcount);
7562 if (dr_feature_refcount != indirect_vdev_count) {
7563 ret = 1;
7564 (void) printf("Number of indirect vdevs (%llu) " \
7565 "does not match feature count (%llu)\n",
7566 (u_longlong_t)indirect_vdev_count,
7567 (u_longlong_t)dr_feature_refcount);
7568 } else {
7569 (void) printf("Verified device_removal feature refcount " \
7570 "of %llu is correct\n",
7571 (u_longlong_t)dr_feature_refcount);
7574 if (zap_contains(spa_meta_objset(spa), DMU_POOL_DIRECTORY_OBJECT,
7575 DMU_POOL_OBSOLETE_BPOBJ) == 0) {
7576 obsolete_bpobj_count++;
7580 obsolete_counts_object_count = precise_vdev_count;
7581 obsolete_counts_object_count += obsolete_sm_count;
7582 obsolete_counts_object_count += obsolete_counts_count;
7583 obsolete_counts_object_count += scip_count;
7584 obsolete_counts_object_count += obsolete_bpobj_count;
7585 obsolete_counts_object_count += remap_deadlist_count;
7587 if (oc_feature_refcount != obsolete_counts_object_count) {
7588 ret = 1;
7589 (void) printf("Number of obsolete counts objects (%llu) " \
7590 "does not match feature count (%llu)\n",
7591 (u_longlong_t)obsolete_counts_object_count,
7592 (u_longlong_t)oc_feature_refcount);
7593 (void) printf("pv:%llu os:%llu oc:%llu sc:%llu "
7594 "ob:%llu rd:%llu\n",
7595 (u_longlong_t)precise_vdev_count,
7596 (u_longlong_t)obsolete_sm_count,
7597 (u_longlong_t)obsolete_counts_count,
7598 (u_longlong_t)scip_count,
7599 (u_longlong_t)obsolete_bpobj_count,
7600 (u_longlong_t)remap_deadlist_count);
7601 } else {
7602 (void) printf("Verified indirect_refcount feature refcount " \
7603 "of %llu is correct\n",
7604 (u_longlong_t)oc_feature_refcount);
7606 return (ret);
7609 static void
7610 zdb_set_skip_mmp(char *target)
7612 spa_t *spa;
7615 * Disable the activity check to allow examination of
7616 * active pools.
7618 mutex_enter(&spa_namespace_lock);
7619 if ((spa = spa_lookup(target)) != NULL) {
7620 spa->spa_import_flags |= ZFS_IMPORT_SKIP_MMP;
7622 mutex_exit(&spa_namespace_lock);
7625 #define BOGUS_SUFFIX "_CHECKPOINTED_UNIVERSE"
7627 * Import the checkpointed state of the pool specified by the target
7628 * parameter as readonly. The function also accepts a pool config
7629 * as an optional parameter, else it attempts to infer the config by
7630 * the name of the target pool.
7632 * Note that the checkpointed state's pool name will be the name of
7633 * the original pool with the above suffix appended to it. In addition,
7634 * if the target is not a pool name (e.g. a path to a dataset) then
7635 * the new_path parameter is populated with the updated path to
7636 * reflect the fact that we are looking into the checkpointed state.
7638 * The function returns a newly-allocated copy of the name of the
7639 * pool containing the checkpointed state. When this copy is no
7640 * longer needed it should be freed with free(3C). Same thing
7641 * applies to the new_path parameter if allocated.
7643 static char *
7644 import_checkpointed_state(char *target, nvlist_t *cfg, char **new_path)
7646 int error = 0;
7647 char *poolname, *bogus_name = NULL;
7648 boolean_t freecfg = B_FALSE;
7650 /* If the target is not a pool, the extract the pool name */
7651 char *path_start = strchr(target, '/');
7652 if (path_start != NULL) {
7653 size_t poolname_len = path_start - target;
7654 poolname = strndup(target, poolname_len);
7655 } else {
7656 poolname = target;
7659 if (cfg == NULL) {
7660 zdb_set_skip_mmp(poolname);
7661 error = spa_get_stats(poolname, &cfg, NULL, 0);
7662 if (error != 0) {
7663 fatal("Tried to read config of pool \"%s\" but "
7664 "spa_get_stats() failed with error %d\n",
7665 poolname, error);
7667 freecfg = B_TRUE;
7670 if (asprintf(&bogus_name, "%s%s", poolname, BOGUS_SUFFIX) == -1) {
7671 if (target != poolname)
7672 free(poolname);
7673 return (NULL);
7675 fnvlist_add_string(cfg, ZPOOL_CONFIG_POOL_NAME, bogus_name);
7677 error = spa_import(bogus_name, cfg, NULL,
7678 ZFS_IMPORT_MISSING_LOG | ZFS_IMPORT_CHECKPOINT |
7679 ZFS_IMPORT_SKIP_MMP);
7680 if (freecfg)
7681 nvlist_free(cfg);
7682 if (error != 0) {
7683 fatal("Tried to import pool \"%s\" but spa_import() failed "
7684 "with error %d\n", bogus_name, error);
7687 if (new_path != NULL && path_start != NULL) {
7688 if (asprintf(new_path, "%s%s", bogus_name, path_start) == -1) {
7689 free(bogus_name);
7690 if (path_start != NULL)
7691 free(poolname);
7692 return (NULL);
7696 if (target != poolname)
7697 free(poolname);
7699 return (bogus_name);
7702 typedef struct verify_checkpoint_sm_entry_cb_arg {
7703 vdev_t *vcsec_vd;
7705 /* the following fields are only used for printing progress */
7706 uint64_t vcsec_entryid;
7707 uint64_t vcsec_num_entries;
7708 } verify_checkpoint_sm_entry_cb_arg_t;
7710 #define ENTRIES_PER_PROGRESS_UPDATE 10000
7712 static int
7713 verify_checkpoint_sm_entry_cb(space_map_entry_t *sme, void *arg)
7715 verify_checkpoint_sm_entry_cb_arg_t *vcsec = arg;
7716 vdev_t *vd = vcsec->vcsec_vd;
7717 metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
7718 uint64_t end = sme->sme_offset + sme->sme_run;
7720 ASSERT(sme->sme_type == SM_FREE);
7722 if ((vcsec->vcsec_entryid % ENTRIES_PER_PROGRESS_UPDATE) == 0) {
7723 (void) fprintf(stderr,
7724 "\rverifying vdev %llu, space map entry %llu of %llu ...",
7725 (longlong_t)vd->vdev_id,
7726 (longlong_t)vcsec->vcsec_entryid,
7727 (longlong_t)vcsec->vcsec_num_entries);
7729 vcsec->vcsec_entryid++;
7732 * See comment in checkpoint_sm_exclude_entry_cb()
7734 VERIFY3U(sme->sme_offset, >=, ms->ms_start);
7735 VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
7738 * The entries in the vdev_checkpoint_sm should be marked as
7739 * allocated in the checkpointed state of the pool, therefore
7740 * their respective ms_allocateable trees should not contain them.
7742 mutex_enter(&ms->ms_lock);
7743 range_tree_verify_not_present(ms->ms_allocatable,
7744 sme->sme_offset, sme->sme_run);
7745 mutex_exit(&ms->ms_lock);
7747 return (0);
7751 * Verify that all segments in the vdev_checkpoint_sm are allocated
7752 * according to the checkpoint's ms_sm (i.e. are not in the checkpoint's
7753 * ms_allocatable).
7755 * Do so by comparing the checkpoint space maps (vdev_checkpoint_sm) of
7756 * each vdev in the current state of the pool to the metaslab space maps
7757 * (ms_sm) of the checkpointed state of the pool.
7759 * Note that the function changes the state of the ms_allocatable
7760 * trees of the current spa_t. The entries of these ms_allocatable
7761 * trees are cleared out and then repopulated from with the free
7762 * entries of their respective ms_sm space maps.
7764 static void
7765 verify_checkpoint_vdev_spacemaps(spa_t *checkpoint, spa_t *current)
7767 vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
7768 vdev_t *current_rvd = current->spa_root_vdev;
7770 load_concrete_ms_allocatable_trees(checkpoint, SM_FREE);
7772 for (uint64_t c = 0; c < ckpoint_rvd->vdev_children; c++) {
7773 vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[c];
7774 vdev_t *current_vd = current_rvd->vdev_child[c];
7776 space_map_t *checkpoint_sm = NULL;
7777 uint64_t checkpoint_sm_obj;
7779 if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
7781 * Since we don't allow device removal in a pool
7782 * that has a checkpoint, we expect that all removed
7783 * vdevs were removed from the pool before the
7784 * checkpoint.
7786 ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
7787 continue;
7791 * If the checkpoint space map doesn't exist, then nothing
7792 * here is checkpointed so there's nothing to verify.
7794 if (current_vd->vdev_top_zap == 0 ||
7795 zap_contains(spa_meta_objset(current),
7796 current_vd->vdev_top_zap,
7797 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
7798 continue;
7800 VERIFY0(zap_lookup(spa_meta_objset(current),
7801 current_vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
7802 sizeof (uint64_t), 1, &checkpoint_sm_obj));
7804 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(current),
7805 checkpoint_sm_obj, 0, current_vd->vdev_asize,
7806 current_vd->vdev_ashift));
7808 verify_checkpoint_sm_entry_cb_arg_t vcsec;
7809 vcsec.vcsec_vd = ckpoint_vd;
7810 vcsec.vcsec_entryid = 0;
7811 vcsec.vcsec_num_entries =
7812 space_map_length(checkpoint_sm) / sizeof (uint64_t);
7813 VERIFY0(space_map_iterate(checkpoint_sm,
7814 space_map_length(checkpoint_sm),
7815 verify_checkpoint_sm_entry_cb, &vcsec));
7816 if (dump_opt['m'] > 3)
7817 dump_spacemap(current->spa_meta_objset, checkpoint_sm);
7818 space_map_close(checkpoint_sm);
7822 * If we've added vdevs since we took the checkpoint, ensure
7823 * that their checkpoint space maps are empty.
7825 if (ckpoint_rvd->vdev_children < current_rvd->vdev_children) {
7826 for (uint64_t c = ckpoint_rvd->vdev_children;
7827 c < current_rvd->vdev_children; c++) {
7828 vdev_t *current_vd = current_rvd->vdev_child[c];
7829 VERIFY3P(current_vd->vdev_checkpoint_sm, ==, NULL);
7833 /* for cleaner progress output */
7834 (void) fprintf(stderr, "\n");
7838 * Verifies that all space that's allocated in the checkpoint is
7839 * still allocated in the current version, by checking that everything
7840 * in checkpoint's ms_allocatable (which is actually allocated, not
7841 * allocatable/free) is not present in current's ms_allocatable.
7843 * Note that the function changes the state of the ms_allocatable
7844 * trees of both spas when called. The entries of all ms_allocatable
7845 * trees are cleared out and then repopulated from their respective
7846 * ms_sm space maps. In the checkpointed state we load the allocated
7847 * entries, and in the current state we load the free entries.
7849 static void
7850 verify_checkpoint_ms_spacemaps(spa_t *checkpoint, spa_t *current)
7852 vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
7853 vdev_t *current_rvd = current->spa_root_vdev;
7855 load_concrete_ms_allocatable_trees(checkpoint, SM_ALLOC);
7856 load_concrete_ms_allocatable_trees(current, SM_FREE);
7858 for (uint64_t i = 0; i < ckpoint_rvd->vdev_children; i++) {
7859 vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[i];
7860 vdev_t *current_vd = current_rvd->vdev_child[i];
7862 if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
7864 * See comment in verify_checkpoint_vdev_spacemaps()
7866 ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
7867 continue;
7870 for (uint64_t m = 0; m < ckpoint_vd->vdev_ms_count; m++) {
7871 metaslab_t *ckpoint_msp = ckpoint_vd->vdev_ms[m];
7872 metaslab_t *current_msp = current_vd->vdev_ms[m];
7874 (void) fprintf(stderr,
7875 "\rverifying vdev %llu of %llu, "
7876 "metaslab %llu of %llu ...",
7877 (longlong_t)current_vd->vdev_id,
7878 (longlong_t)current_rvd->vdev_children,
7879 (longlong_t)current_vd->vdev_ms[m]->ms_id,
7880 (longlong_t)current_vd->vdev_ms_count);
7883 * We walk through the ms_allocatable trees that
7884 * are loaded with the allocated blocks from the
7885 * ms_sm spacemaps of the checkpoint. For each
7886 * one of these ranges we ensure that none of them
7887 * exists in the ms_allocatable trees of the
7888 * current state which are loaded with the ranges
7889 * that are currently free.
7891 * This way we ensure that none of the blocks that
7892 * are part of the checkpoint were freed by mistake.
7894 range_tree_walk(ckpoint_msp->ms_allocatable,
7895 (range_tree_func_t *)range_tree_verify_not_present,
7896 current_msp->ms_allocatable);
7900 /* for cleaner progress output */
7901 (void) fprintf(stderr, "\n");
7904 static void
7905 verify_checkpoint_blocks(spa_t *spa)
7907 ASSERT(!dump_opt['L']);
7909 spa_t *checkpoint_spa;
7910 char *checkpoint_pool;
7911 int error = 0;
7914 * We import the checkpointed state of the pool (under a different
7915 * name) so we can do verification on it against the current state
7916 * of the pool.
7918 checkpoint_pool = import_checkpointed_state(spa->spa_name, NULL,
7919 NULL);
7920 ASSERT(strcmp(spa->spa_name, checkpoint_pool) != 0);
7922 error = spa_open(checkpoint_pool, &checkpoint_spa, FTAG);
7923 if (error != 0) {
7924 fatal("Tried to open pool \"%s\" but spa_open() failed with "
7925 "error %d\n", checkpoint_pool, error);
7929 * Ensure that ranges in the checkpoint space maps of each vdev
7930 * are allocated according to the checkpointed state's metaslab
7931 * space maps.
7933 verify_checkpoint_vdev_spacemaps(checkpoint_spa, spa);
7936 * Ensure that allocated ranges in the checkpoint's metaslab
7937 * space maps remain allocated in the metaslab space maps of
7938 * the current state.
7940 verify_checkpoint_ms_spacemaps(checkpoint_spa, spa);
7943 * Once we are done, we get rid of the checkpointed state.
7945 spa_close(checkpoint_spa, FTAG);
7946 free(checkpoint_pool);
7949 static void
7950 dump_leftover_checkpoint_blocks(spa_t *spa)
7952 vdev_t *rvd = spa->spa_root_vdev;
7954 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
7955 vdev_t *vd = rvd->vdev_child[i];
7957 space_map_t *checkpoint_sm = NULL;
7958 uint64_t checkpoint_sm_obj;
7960 if (vd->vdev_top_zap == 0)
7961 continue;
7963 if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
7964 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
7965 continue;
7967 VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
7968 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
7969 sizeof (uint64_t), 1, &checkpoint_sm_obj));
7971 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
7972 checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
7973 dump_spacemap(spa->spa_meta_objset, checkpoint_sm);
7974 space_map_close(checkpoint_sm);
7978 static int
7979 verify_checkpoint(spa_t *spa)
7981 uberblock_t checkpoint;
7982 int error;
7984 if (!spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT))
7985 return (0);
7987 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7988 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
7989 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
7991 if (error == ENOENT && !dump_opt['L']) {
7993 * If the feature is active but the uberblock is missing
7994 * then we must be in the middle of discarding the
7995 * checkpoint.
7997 (void) printf("\nPartially discarded checkpoint "
7998 "state found:\n");
7999 if (dump_opt['m'] > 3)
8000 dump_leftover_checkpoint_blocks(spa);
8001 return (0);
8002 } else if (error != 0) {
8003 (void) printf("lookup error %d when looking for "
8004 "checkpointed uberblock in MOS\n", error);
8005 return (error);
8007 dump_uberblock(&checkpoint, "\nCheckpointed uberblock found:\n", "\n");
8009 if (checkpoint.ub_checkpoint_txg == 0) {
8010 (void) printf("\nub_checkpoint_txg not set in checkpointed "
8011 "uberblock\n");
8012 error = 3;
8015 if (error == 0 && !dump_opt['L'])
8016 verify_checkpoint_blocks(spa);
8018 return (error);
8021 static void
8022 mos_leaks_cb(void *arg, uint64_t start, uint64_t size)
8024 (void) arg;
8025 for (uint64_t i = start; i < size; i++) {
8026 (void) printf("MOS object %llu referenced but not allocated\n",
8027 (u_longlong_t)i);
8031 static void
8032 mos_obj_refd(uint64_t obj)
8034 if (obj != 0 && mos_refd_objs != NULL)
8035 range_tree_add(mos_refd_objs, obj, 1);
8039 * Call on a MOS object that may already have been referenced.
8041 static void
8042 mos_obj_refd_multiple(uint64_t obj)
8044 if (obj != 0 && mos_refd_objs != NULL &&
8045 !range_tree_contains(mos_refd_objs, obj, 1))
8046 range_tree_add(mos_refd_objs, obj, 1);
8049 static void
8050 mos_leak_vdev_top_zap(vdev_t *vd)
8052 uint64_t ms_flush_data_obj;
8053 int error = zap_lookup(spa_meta_objset(vd->vdev_spa),
8054 vd->vdev_top_zap, VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS,
8055 sizeof (ms_flush_data_obj), 1, &ms_flush_data_obj);
8056 if (error == ENOENT)
8057 return;
8058 ASSERT0(error);
8060 mos_obj_refd(ms_flush_data_obj);
8063 static void
8064 mos_leak_vdev(vdev_t *vd)
8066 mos_obj_refd(vd->vdev_dtl_object);
8067 mos_obj_refd(vd->vdev_ms_array);
8068 mos_obj_refd(vd->vdev_indirect_config.vic_births_object);
8069 mos_obj_refd(vd->vdev_indirect_config.vic_mapping_object);
8070 mos_obj_refd(vd->vdev_leaf_zap);
8071 if (vd->vdev_checkpoint_sm != NULL)
8072 mos_obj_refd(vd->vdev_checkpoint_sm->sm_object);
8073 if (vd->vdev_indirect_mapping != NULL) {
8074 mos_obj_refd(vd->vdev_indirect_mapping->
8075 vim_phys->vimp_counts_object);
8077 if (vd->vdev_obsolete_sm != NULL)
8078 mos_obj_refd(vd->vdev_obsolete_sm->sm_object);
8080 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
8081 metaslab_t *ms = vd->vdev_ms[m];
8082 mos_obj_refd(space_map_object(ms->ms_sm));
8085 if (vd->vdev_root_zap != 0)
8086 mos_obj_refd(vd->vdev_root_zap);
8088 if (vd->vdev_top_zap != 0) {
8089 mos_obj_refd(vd->vdev_top_zap);
8090 mos_leak_vdev_top_zap(vd);
8093 for (uint64_t c = 0; c < vd->vdev_children; c++) {
8094 mos_leak_vdev(vd->vdev_child[c]);
8098 static void
8099 mos_leak_log_spacemaps(spa_t *spa)
8101 uint64_t spacemap_zap;
8102 int error = zap_lookup(spa_meta_objset(spa),
8103 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_LOG_SPACEMAP_ZAP,
8104 sizeof (spacemap_zap), 1, &spacemap_zap);
8105 if (error == ENOENT)
8106 return;
8107 ASSERT0(error);
8109 mos_obj_refd(spacemap_zap);
8110 for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
8111 sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls))
8112 mos_obj_refd(sls->sls_sm_obj);
8115 static void
8116 errorlog_count_refd(objset_t *mos, uint64_t errlog)
8118 zap_cursor_t zc;
8119 zap_attribute_t *za = zap_attribute_alloc();
8120 for (zap_cursor_init(&zc, mos, errlog);
8121 zap_cursor_retrieve(&zc, za) == 0;
8122 zap_cursor_advance(&zc)) {
8123 mos_obj_refd(za->za_first_integer);
8125 zap_cursor_fini(&zc);
8126 zap_attribute_free(za);
8129 static int
8130 dump_mos_leaks(spa_t *spa)
8132 int rv = 0;
8133 objset_t *mos = spa->spa_meta_objset;
8134 dsl_pool_t *dp = spa->spa_dsl_pool;
8136 /* Visit and mark all referenced objects in the MOS */
8138 mos_obj_refd(DMU_POOL_DIRECTORY_OBJECT);
8139 mos_obj_refd(spa->spa_pool_props_object);
8140 mos_obj_refd(spa->spa_config_object);
8141 mos_obj_refd(spa->spa_ddt_stat_object);
8142 mos_obj_refd(spa->spa_feat_desc_obj);
8143 mos_obj_refd(spa->spa_feat_enabled_txg_obj);
8144 mos_obj_refd(spa->spa_feat_for_read_obj);
8145 mos_obj_refd(spa->spa_feat_for_write_obj);
8146 mos_obj_refd(spa->spa_history);
8147 mos_obj_refd(spa->spa_errlog_last);
8148 mos_obj_refd(spa->spa_errlog_scrub);
8150 if (spa_feature_is_enabled(spa, SPA_FEATURE_HEAD_ERRLOG)) {
8151 errorlog_count_refd(mos, spa->spa_errlog_last);
8152 errorlog_count_refd(mos, spa->spa_errlog_scrub);
8155 mos_obj_refd(spa->spa_all_vdev_zaps);
8156 mos_obj_refd(spa->spa_dsl_pool->dp_bptree_obj);
8157 mos_obj_refd(spa->spa_dsl_pool->dp_tmp_userrefs_obj);
8158 mos_obj_refd(spa->spa_dsl_pool->dp_scan->scn_phys.scn_queue_obj);
8159 bpobj_count_refd(&spa->spa_deferred_bpobj);
8160 mos_obj_refd(dp->dp_empty_bpobj);
8161 bpobj_count_refd(&dp->dp_obsolete_bpobj);
8162 bpobj_count_refd(&dp->dp_free_bpobj);
8163 mos_obj_refd(spa->spa_l2cache.sav_object);
8164 mos_obj_refd(spa->spa_spares.sav_object);
8166 if (spa->spa_syncing_log_sm != NULL)
8167 mos_obj_refd(spa->spa_syncing_log_sm->sm_object);
8168 mos_leak_log_spacemaps(spa);
8170 mos_obj_refd(spa->spa_condensing_indirect_phys.
8171 scip_next_mapping_object);
8172 mos_obj_refd(spa->spa_condensing_indirect_phys.
8173 scip_prev_obsolete_sm_object);
8174 if (spa->spa_condensing_indirect_phys.scip_next_mapping_object != 0) {
8175 vdev_indirect_mapping_t *vim =
8176 vdev_indirect_mapping_open(mos,
8177 spa->spa_condensing_indirect_phys.scip_next_mapping_object);
8178 mos_obj_refd(vim->vim_phys->vimp_counts_object);
8179 vdev_indirect_mapping_close(vim);
8181 deleted_livelists_dump_mos(spa);
8183 if (dp->dp_origin_snap != NULL) {
8184 dsl_dataset_t *ds;
8186 dsl_pool_config_enter(dp, FTAG);
8187 VERIFY0(dsl_dataset_hold_obj(dp,
8188 dsl_dataset_phys(dp->dp_origin_snap)->ds_next_snap_obj,
8189 FTAG, &ds));
8190 count_ds_mos_objects(ds);
8191 dump_blkptr_list(&ds->ds_deadlist, "Deadlist");
8192 dsl_dataset_rele(ds, FTAG);
8193 dsl_pool_config_exit(dp, FTAG);
8195 count_ds_mos_objects(dp->dp_origin_snap);
8196 dump_blkptr_list(&dp->dp_origin_snap->ds_deadlist, "Deadlist");
8198 count_dir_mos_objects(dp->dp_mos_dir);
8199 if (dp->dp_free_dir != NULL)
8200 count_dir_mos_objects(dp->dp_free_dir);
8201 if (dp->dp_leak_dir != NULL)
8202 count_dir_mos_objects(dp->dp_leak_dir);
8204 mos_leak_vdev(spa->spa_root_vdev);
8206 for (uint64_t c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
8207 ddt_t *ddt = spa->spa_ddt[c];
8208 if (!ddt || ddt->ddt_version == DDT_VERSION_UNCONFIGURED)
8209 continue;
8211 /* DDT store objects */
8212 for (ddt_type_t type = 0; type < DDT_TYPES; type++) {
8213 for (ddt_class_t class = 0; class < DDT_CLASSES;
8214 class++) {
8215 mos_obj_refd(ddt->ddt_object[type][class]);
8219 /* FDT container */
8220 if (ddt->ddt_version == DDT_VERSION_FDT)
8221 mos_obj_refd(ddt->ddt_dir_object);
8223 /* FDT log objects */
8224 if (ddt->ddt_flags & DDT_FLAG_LOG) {
8225 mos_obj_refd(ddt->ddt_log[0].ddl_object);
8226 mos_obj_refd(ddt->ddt_log[1].ddl_object);
8230 if (spa->spa_brt != NULL) {
8231 brt_t *brt = spa->spa_brt;
8232 for (uint64_t vdevid = 0; vdevid < brt->brt_nvdevs; vdevid++) {
8233 brt_vdev_t *brtvd = &brt->brt_vdevs[vdevid];
8234 if (brtvd != NULL && brtvd->bv_initiated) {
8235 mos_obj_refd(brtvd->bv_mos_brtvdev);
8236 mos_obj_refd(brtvd->bv_mos_entries);
8242 * Visit all allocated objects and make sure they are referenced.
8244 uint64_t object = 0;
8245 while (dmu_object_next(mos, &object, B_FALSE, 0) == 0) {
8246 if (range_tree_contains(mos_refd_objs, object, 1)) {
8247 range_tree_remove(mos_refd_objs, object, 1);
8248 } else {
8249 dmu_object_info_t doi;
8250 const char *name;
8251 VERIFY0(dmu_object_info(mos, object, &doi));
8252 if (doi.doi_type & DMU_OT_NEWTYPE) {
8253 dmu_object_byteswap_t bswap =
8254 DMU_OT_BYTESWAP(doi.doi_type);
8255 name = dmu_ot_byteswap[bswap].ob_name;
8256 } else {
8257 name = dmu_ot[doi.doi_type].ot_name;
8260 (void) printf("MOS object %llu (%s) leaked\n",
8261 (u_longlong_t)object, name);
8262 rv = 2;
8265 (void) range_tree_walk(mos_refd_objs, mos_leaks_cb, NULL);
8266 if (!range_tree_is_empty(mos_refd_objs))
8267 rv = 2;
8268 range_tree_vacate(mos_refd_objs, NULL, NULL);
8269 range_tree_destroy(mos_refd_objs);
8270 return (rv);
8273 typedef struct log_sm_obsolete_stats_arg {
8274 uint64_t lsos_current_txg;
8276 uint64_t lsos_total_entries;
8277 uint64_t lsos_valid_entries;
8279 uint64_t lsos_sm_entries;
8280 uint64_t lsos_valid_sm_entries;
8281 } log_sm_obsolete_stats_arg_t;
8283 static int
8284 log_spacemap_obsolete_stats_cb(spa_t *spa, space_map_entry_t *sme,
8285 uint64_t txg, void *arg)
8287 log_sm_obsolete_stats_arg_t *lsos = arg;
8289 uint64_t offset = sme->sme_offset;
8290 uint64_t vdev_id = sme->sme_vdev;
8292 if (lsos->lsos_current_txg == 0) {
8293 /* this is the first log */
8294 lsos->lsos_current_txg = txg;
8295 } else if (lsos->lsos_current_txg < txg) {
8296 /* we just changed log - print stats and reset */
8297 (void) printf("%-8llu valid entries out of %-8llu - txg %llu\n",
8298 (u_longlong_t)lsos->lsos_valid_sm_entries,
8299 (u_longlong_t)lsos->lsos_sm_entries,
8300 (u_longlong_t)lsos->lsos_current_txg);
8301 lsos->lsos_valid_sm_entries = 0;
8302 lsos->lsos_sm_entries = 0;
8303 lsos->lsos_current_txg = txg;
8305 ASSERT3U(lsos->lsos_current_txg, ==, txg);
8307 lsos->lsos_sm_entries++;
8308 lsos->lsos_total_entries++;
8310 vdev_t *vd = vdev_lookup_top(spa, vdev_id);
8311 if (!vdev_is_concrete(vd))
8312 return (0);
8314 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
8315 ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
8317 if (txg < metaslab_unflushed_txg(ms))
8318 return (0);
8319 lsos->lsos_valid_sm_entries++;
8320 lsos->lsos_valid_entries++;
8321 return (0);
8324 static void
8325 dump_log_spacemap_obsolete_stats(spa_t *spa)
8327 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
8328 return;
8330 log_sm_obsolete_stats_arg_t lsos = {0};
8332 (void) printf("Log Space Map Obsolete Entry Statistics:\n");
8334 iterate_through_spacemap_logs(spa,
8335 log_spacemap_obsolete_stats_cb, &lsos);
8337 /* print stats for latest log */
8338 (void) printf("%-8llu valid entries out of %-8llu - txg %llu\n",
8339 (u_longlong_t)lsos.lsos_valid_sm_entries,
8340 (u_longlong_t)lsos.lsos_sm_entries,
8341 (u_longlong_t)lsos.lsos_current_txg);
8343 (void) printf("%-8llu valid entries out of %-8llu - total\n\n",
8344 (u_longlong_t)lsos.lsos_valid_entries,
8345 (u_longlong_t)lsos.lsos_total_entries);
8348 static void
8349 dump_zpool(spa_t *spa)
8351 dsl_pool_t *dp = spa_get_dsl(spa);
8352 int rc = 0;
8354 if (dump_opt['y']) {
8355 livelist_metaslab_validate(spa);
8358 if (dump_opt['S']) {
8359 dump_simulated_ddt(spa);
8360 return;
8363 if (!dump_opt['e'] && dump_opt['C'] > 1) {
8364 (void) printf("\nCached configuration:\n");
8365 dump_nvlist(spa->spa_config, 8);
8368 if (dump_opt['C'])
8369 dump_config(spa);
8371 if (dump_opt['u'])
8372 dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
8374 if (dump_opt['D'])
8375 dump_all_ddts(spa);
8377 if (dump_opt['T'])
8378 dump_brt(spa);
8380 if (dump_opt['d'] > 2 || dump_opt['m'])
8381 dump_metaslabs(spa);
8382 if (dump_opt['M'])
8383 dump_metaslab_groups(spa, dump_opt['M'] > 1);
8384 if (dump_opt['d'] > 2 || dump_opt['m']) {
8385 dump_log_spacemaps(spa);
8386 dump_log_spacemap_obsolete_stats(spa);
8389 if (dump_opt['d'] || dump_opt['i']) {
8390 spa_feature_t f;
8391 mos_refd_objs = range_tree_create(NULL, RANGE_SEG64, NULL, 0,
8393 dump_objset(dp->dp_meta_objset);
8395 if (dump_opt['d'] >= 3) {
8396 dsl_pool_t *dp = spa->spa_dsl_pool;
8397 dump_full_bpobj(&spa->spa_deferred_bpobj,
8398 "Deferred frees", 0);
8399 if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
8400 dump_full_bpobj(&dp->dp_free_bpobj,
8401 "Pool snapshot frees", 0);
8403 if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
8404 ASSERT(spa_feature_is_enabled(spa,
8405 SPA_FEATURE_DEVICE_REMOVAL));
8406 dump_full_bpobj(&dp->dp_obsolete_bpobj,
8407 "Pool obsolete blocks", 0);
8410 if (spa_feature_is_active(spa,
8411 SPA_FEATURE_ASYNC_DESTROY)) {
8412 dump_bptree(spa->spa_meta_objset,
8413 dp->dp_bptree_obj,
8414 "Pool dataset frees");
8416 dump_dtl(spa->spa_root_vdev, 0);
8419 for (spa_feature_t f = 0; f < SPA_FEATURES; f++)
8420 global_feature_count[f] = UINT64_MAX;
8421 global_feature_count[SPA_FEATURE_REDACTION_BOOKMARKS] = 0;
8422 global_feature_count[SPA_FEATURE_REDACTION_LIST_SPILL] = 0;
8423 global_feature_count[SPA_FEATURE_BOOKMARK_WRITTEN] = 0;
8424 global_feature_count[SPA_FEATURE_LIVELIST] = 0;
8426 (void) dmu_objset_find(spa_name(spa), dump_one_objset,
8427 NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
8429 if (rc == 0 && !dump_opt['L'])
8430 rc = dump_mos_leaks(spa);
8432 for (f = 0; f < SPA_FEATURES; f++) {
8433 uint64_t refcount;
8435 uint64_t *arr;
8436 if (!(spa_feature_table[f].fi_flags &
8437 ZFEATURE_FLAG_PER_DATASET)) {
8438 if (global_feature_count[f] == UINT64_MAX)
8439 continue;
8440 if (!spa_feature_is_enabled(spa, f)) {
8441 ASSERT0(global_feature_count[f]);
8442 continue;
8444 arr = global_feature_count;
8445 } else {
8446 if (!spa_feature_is_enabled(spa, f)) {
8447 ASSERT0(dataset_feature_count[f]);
8448 continue;
8450 arr = dataset_feature_count;
8452 if (feature_get_refcount(spa, &spa_feature_table[f],
8453 &refcount) == ENOTSUP)
8454 continue;
8455 if (arr[f] != refcount) {
8456 (void) printf("%s feature refcount mismatch: "
8457 "%lld consumers != %lld refcount\n",
8458 spa_feature_table[f].fi_uname,
8459 (longlong_t)arr[f], (longlong_t)refcount);
8460 rc = 2;
8461 } else {
8462 (void) printf("Verified %s feature refcount "
8463 "of %llu is correct\n",
8464 spa_feature_table[f].fi_uname,
8465 (longlong_t)refcount);
8469 if (rc == 0)
8470 rc = verify_device_removal_feature_counts(spa);
8473 if (rc == 0 && (dump_opt['b'] || dump_opt['c']))
8474 rc = dump_block_stats(spa);
8476 if (rc == 0)
8477 rc = verify_spacemap_refcounts(spa);
8479 if (dump_opt['s'])
8480 show_pool_stats(spa);
8482 if (dump_opt['h'])
8483 dump_history(spa);
8485 if (rc == 0)
8486 rc = verify_checkpoint(spa);
8488 if (rc != 0) {
8489 dump_debug_buffer();
8490 zdb_exit(rc);
8494 #define ZDB_FLAG_CHECKSUM 0x0001
8495 #define ZDB_FLAG_DECOMPRESS 0x0002
8496 #define ZDB_FLAG_BSWAP 0x0004
8497 #define ZDB_FLAG_GBH 0x0008
8498 #define ZDB_FLAG_INDIRECT 0x0010
8499 #define ZDB_FLAG_RAW 0x0020
8500 #define ZDB_FLAG_PRINT_BLKPTR 0x0040
8501 #define ZDB_FLAG_VERBOSE 0x0080
8503 static int flagbits[256];
8504 static char flagbitstr[16];
8506 static void
8507 zdb_print_blkptr(const blkptr_t *bp, int flags)
8509 char blkbuf[BP_SPRINTF_LEN];
8511 if (flags & ZDB_FLAG_BSWAP)
8512 byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
8514 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
8515 (void) printf("%s\n", blkbuf);
8518 static void
8519 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
8521 int i;
8523 for (i = 0; i < nbps; i++)
8524 zdb_print_blkptr(&bp[i], flags);
8527 static void
8528 zdb_dump_gbh(void *buf, int flags)
8530 zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
8533 static void
8534 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
8536 if (flags & ZDB_FLAG_BSWAP)
8537 byteswap_uint64_array(buf, size);
8538 VERIFY(write(fileno(stdout), buf, size) == size);
8541 static void
8542 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
8544 uint64_t *d = (uint64_t *)buf;
8545 unsigned nwords = size / sizeof (uint64_t);
8546 int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
8547 unsigned i, j;
8548 const char *hdr;
8549 char *c;
8552 if (do_bswap)
8553 hdr = " 7 6 5 4 3 2 1 0 f e d c b a 9 8";
8554 else
8555 hdr = " 0 1 2 3 4 5 6 7 8 9 a b c d e f";
8557 (void) printf("\n%s\n%6s %s 0123456789abcdef\n", label, "", hdr);
8559 #ifdef _ZFS_LITTLE_ENDIAN
8560 /* correct the endianness */
8561 do_bswap = !do_bswap;
8562 #endif
8563 for (i = 0; i < nwords; i += 2) {
8564 (void) printf("%06llx: %016llx %016llx ",
8565 (u_longlong_t)(i * sizeof (uint64_t)),
8566 (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
8567 (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
8569 c = (char *)&d[i];
8570 for (j = 0; j < 2 * sizeof (uint64_t); j++)
8571 (void) printf("%c", isprint(c[j]) ? c[j] : '.');
8572 (void) printf("\n");
8577 * There are two acceptable formats:
8578 * leaf_name - For example: c1t0d0 or /tmp/ztest.0a
8579 * child[.child]* - For example: 0.1.1
8581 * The second form can be used to specify arbitrary vdevs anywhere
8582 * in the hierarchy. For example, in a pool with a mirror of
8583 * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
8585 static vdev_t *
8586 zdb_vdev_lookup(vdev_t *vdev, const char *path)
8588 char *s, *p, *q;
8589 unsigned i;
8591 if (vdev == NULL)
8592 return (NULL);
8594 /* First, assume the x.x.x.x format */
8595 i = strtoul(path, &s, 10);
8596 if (s == path || (s && *s != '.' && *s != '\0'))
8597 goto name;
8598 if (i >= vdev->vdev_children)
8599 return (NULL);
8601 vdev = vdev->vdev_child[i];
8602 if (s && *s == '\0')
8603 return (vdev);
8604 return (zdb_vdev_lookup(vdev, s+1));
8606 name:
8607 for (i = 0; i < vdev->vdev_children; i++) {
8608 vdev_t *vc = vdev->vdev_child[i];
8610 if (vc->vdev_path == NULL) {
8611 vc = zdb_vdev_lookup(vc, path);
8612 if (vc == NULL)
8613 continue;
8614 else
8615 return (vc);
8618 p = strrchr(vc->vdev_path, '/');
8619 p = p ? p + 1 : vc->vdev_path;
8620 q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
8622 if (strcmp(vc->vdev_path, path) == 0)
8623 return (vc);
8624 if (strcmp(p, path) == 0)
8625 return (vc);
8626 if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
8627 return (vc);
8630 return (NULL);
8633 static int
8634 name_from_objset_id(spa_t *spa, uint64_t objset_id, char *outstr)
8636 dsl_dataset_t *ds;
8638 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
8639 int error = dsl_dataset_hold_obj(spa->spa_dsl_pool, objset_id,
8640 NULL, &ds);
8641 if (error != 0) {
8642 (void) fprintf(stderr, "failed to hold objset %llu: %s\n",
8643 (u_longlong_t)objset_id, strerror(error));
8644 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
8645 return (error);
8647 dsl_dataset_name(ds, outstr);
8648 dsl_dataset_rele(ds, NULL);
8649 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
8650 return (0);
8653 static boolean_t
8654 zdb_parse_block_sizes(char *sizes, uint64_t *lsize, uint64_t *psize)
8656 char *s0, *s1, *tmp = NULL;
8658 if (sizes == NULL)
8659 return (B_FALSE);
8661 s0 = strtok_r(sizes, "/", &tmp);
8662 if (s0 == NULL)
8663 return (B_FALSE);
8664 s1 = strtok_r(NULL, "/", &tmp);
8665 *lsize = strtoull(s0, NULL, 16);
8666 *psize = s1 ? strtoull(s1, NULL, 16) : *lsize;
8667 return (*lsize >= *psize && *psize > 0);
8670 #define ZIO_COMPRESS_MASK(alg) (1ULL << (ZIO_COMPRESS_##alg))
8672 static boolean_t
8673 try_decompress_block(abd_t *pabd, uint64_t lsize, uint64_t psize,
8674 int flags, int cfunc, void *lbuf, void *lbuf2)
8676 if (flags & ZDB_FLAG_VERBOSE) {
8677 (void) fprintf(stderr,
8678 "Trying %05llx -> %05llx (%s)\n",
8679 (u_longlong_t)psize,
8680 (u_longlong_t)lsize,
8681 zio_compress_table[cfunc].ci_name);
8685 * We set lbuf to all zeros and lbuf2 to all
8686 * ones, then decompress to both buffers and
8687 * compare their contents. This way we can
8688 * know if decompression filled exactly to
8689 * lsize or if it left some bytes unwritten.
8692 memset(lbuf, 0x00, lsize);
8693 memset(lbuf2, 0xff, lsize);
8695 abd_t labd, labd2;
8696 abd_get_from_buf_struct(&labd, lbuf, lsize);
8697 abd_get_from_buf_struct(&labd2, lbuf2, lsize);
8699 boolean_t ret = B_FALSE;
8700 if (zio_decompress_data(cfunc, pabd,
8701 &labd, psize, lsize, NULL) == 0 &&
8702 zio_decompress_data(cfunc, pabd,
8703 &labd2, psize, lsize, NULL) == 0 &&
8704 memcmp(lbuf, lbuf2, lsize) == 0)
8705 ret = B_TRUE;
8707 abd_free(&labd2);
8708 abd_free(&labd);
8710 return (ret);
8713 static uint64_t
8714 zdb_decompress_block(abd_t *pabd, void *buf, void *lbuf, uint64_t lsize,
8715 uint64_t psize, int flags)
8717 (void) buf;
8718 uint64_t orig_lsize = lsize;
8719 boolean_t tryzle = ((getenv("ZDB_NO_ZLE") == NULL));
8720 boolean_t found = B_FALSE;
8722 * We don't know how the data was compressed, so just try
8723 * every decompress function at every inflated blocksize.
8725 void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
8726 int cfuncs[ZIO_COMPRESS_FUNCTIONS] = { 0 };
8727 int *cfuncp = cfuncs;
8728 uint64_t maxlsize = SPA_MAXBLOCKSIZE;
8729 uint64_t mask = ZIO_COMPRESS_MASK(ON) | ZIO_COMPRESS_MASK(OFF) |
8730 ZIO_COMPRESS_MASK(INHERIT) | ZIO_COMPRESS_MASK(EMPTY) |
8731 ZIO_COMPRESS_MASK(ZLE);
8732 *cfuncp++ = ZIO_COMPRESS_LZ4;
8733 *cfuncp++ = ZIO_COMPRESS_LZJB;
8734 mask |= ZIO_COMPRESS_MASK(LZ4) | ZIO_COMPRESS_MASK(LZJB);
8736 * Every gzip level has the same decompressor, no need to
8737 * run it 9 times per bruteforce attempt.
8739 mask |= ZIO_COMPRESS_MASK(GZIP_2) | ZIO_COMPRESS_MASK(GZIP_3);
8740 mask |= ZIO_COMPRESS_MASK(GZIP_4) | ZIO_COMPRESS_MASK(GZIP_5);
8741 mask |= ZIO_COMPRESS_MASK(GZIP_6) | ZIO_COMPRESS_MASK(GZIP_7);
8742 mask |= ZIO_COMPRESS_MASK(GZIP_8) | ZIO_COMPRESS_MASK(GZIP_9);
8743 for (int c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++)
8744 if (((1ULL << c) & mask) == 0)
8745 *cfuncp++ = c;
8748 * On the one hand, with SPA_MAXBLOCKSIZE at 16MB, this
8749 * could take a while and we should let the user know
8750 * we are not stuck. On the other hand, printing progress
8751 * info gets old after a while. User can specify 'v' flag
8752 * to see the progression.
8754 if (lsize == psize)
8755 lsize += SPA_MINBLOCKSIZE;
8756 else
8757 maxlsize = lsize;
8759 for (; lsize <= maxlsize; lsize += SPA_MINBLOCKSIZE) {
8760 for (cfuncp = cfuncs; *cfuncp; cfuncp++) {
8761 if (try_decompress_block(pabd, lsize, psize, flags,
8762 *cfuncp, lbuf, lbuf2)) {
8763 found = B_TRUE;
8764 break;
8767 if (*cfuncp != 0)
8768 break;
8770 if (!found && tryzle) {
8771 for (lsize = orig_lsize; lsize <= maxlsize;
8772 lsize += SPA_MINBLOCKSIZE) {
8773 if (try_decompress_block(pabd, lsize, psize, flags,
8774 ZIO_COMPRESS_ZLE, lbuf, lbuf2)) {
8775 *cfuncp = ZIO_COMPRESS_ZLE;
8776 found = B_TRUE;
8777 break;
8781 umem_free(lbuf2, SPA_MAXBLOCKSIZE);
8783 if (*cfuncp == ZIO_COMPRESS_ZLE) {
8784 printf("\nZLE decompression was selected. If you "
8785 "suspect the results are wrong,\ntry avoiding ZLE "
8786 "by setting and exporting ZDB_NO_ZLE=\"true\"\n");
8789 return (lsize > maxlsize ? -1 : lsize);
8793 * Read a block from a pool and print it out. The syntax of the
8794 * block descriptor is:
8796 * pool:vdev_specifier:offset:[lsize/]psize[:flags]
8798 * pool - The name of the pool you wish to read from
8799 * vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
8800 * offset - offset, in hex, in bytes
8801 * size - Amount of data to read, in hex, in bytes
8802 * flags - A string of characters specifying options
8803 * b: Decode a blkptr at given offset within block
8804 * c: Calculate and display checksums
8805 * d: Decompress data before dumping
8806 * e: Byteswap data before dumping
8807 * g: Display data as a gang block header
8808 * i: Display as an indirect block
8809 * r: Dump raw data to stdout
8810 * v: Verbose
8813 static void
8814 zdb_read_block(char *thing, spa_t *spa)
8816 blkptr_t blk, *bp = &blk;
8817 dva_t *dva = bp->blk_dva;
8818 int flags = 0;
8819 uint64_t offset = 0, psize = 0, lsize = 0, blkptr_offset = 0;
8820 zio_t *zio;
8821 vdev_t *vd;
8822 abd_t *pabd;
8823 void *lbuf, *buf;
8824 char *s, *p, *dup, *flagstr, *sizes, *tmp = NULL;
8825 const char *vdev, *errmsg = NULL;
8826 int i, len, error;
8827 boolean_t borrowed = B_FALSE, found = B_FALSE;
8829 dup = strdup(thing);
8830 s = strtok_r(dup, ":", &tmp);
8831 vdev = s ?: "";
8832 s = strtok_r(NULL, ":", &tmp);
8833 offset = strtoull(s ? s : "", NULL, 16);
8834 sizes = strtok_r(NULL, ":", &tmp);
8835 s = strtok_r(NULL, ":", &tmp);
8836 flagstr = strdup(s ?: "");
8838 if (!zdb_parse_block_sizes(sizes, &lsize, &psize))
8839 errmsg = "invalid size(s)";
8840 if (!IS_P2ALIGNED(psize, DEV_BSIZE) || !IS_P2ALIGNED(lsize, DEV_BSIZE))
8841 errmsg = "size must be a multiple of sector size";
8842 if (!IS_P2ALIGNED(offset, DEV_BSIZE))
8843 errmsg = "offset must be a multiple of sector size";
8844 if (errmsg) {
8845 (void) printf("Invalid block specifier: %s - %s\n",
8846 thing, errmsg);
8847 goto done;
8850 tmp = NULL;
8851 for (s = strtok_r(flagstr, ":", &tmp);
8852 s != NULL;
8853 s = strtok_r(NULL, ":", &tmp)) {
8854 len = strlen(flagstr);
8855 for (i = 0; i < len; i++) {
8856 int bit = flagbits[(uchar_t)flagstr[i]];
8858 if (bit == 0) {
8859 (void) printf("***Ignoring flag: %c\n",
8860 (uchar_t)flagstr[i]);
8861 continue;
8863 found = B_TRUE;
8864 flags |= bit;
8866 p = &flagstr[i + 1];
8867 if (*p != ':' && *p != '\0') {
8868 int j = 0, nextbit = flagbits[(uchar_t)*p];
8869 char *end, offstr[8] = { 0 };
8870 if ((bit == ZDB_FLAG_PRINT_BLKPTR) &&
8871 (nextbit == 0)) {
8872 /* look ahead to isolate the offset */
8873 while (nextbit == 0 &&
8874 strchr(flagbitstr, *p) == NULL) {
8875 offstr[j] = *p;
8876 j++;
8877 if (i + j > strlen(flagstr))
8878 break;
8879 p++;
8880 nextbit = flagbits[(uchar_t)*p];
8882 blkptr_offset = strtoull(offstr, &end,
8883 16);
8884 i += j;
8885 } else if (nextbit == 0) {
8886 (void) printf("***Ignoring flag arg:"
8887 " '%c'\n", (uchar_t)*p);
8892 if (blkptr_offset % sizeof (blkptr_t)) {
8893 printf("Block pointer offset 0x%llx "
8894 "must be divisible by 0x%x\n",
8895 (longlong_t)blkptr_offset, (int)sizeof (blkptr_t));
8896 goto done;
8898 if (found == B_FALSE && strlen(flagstr) > 0) {
8899 printf("Invalid flag arg: '%s'\n", flagstr);
8900 goto done;
8903 vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
8904 if (vd == NULL) {
8905 (void) printf("***Invalid vdev: %s\n", vdev);
8906 goto done;
8907 } else {
8908 if (vd->vdev_path)
8909 (void) fprintf(stderr, "Found vdev: %s\n",
8910 vd->vdev_path);
8911 else
8912 (void) fprintf(stderr, "Found vdev type: %s\n",
8913 vd->vdev_ops->vdev_op_type);
8916 pabd = abd_alloc_for_io(SPA_MAXBLOCKSIZE, B_FALSE);
8917 lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
8919 BP_ZERO(bp);
8921 DVA_SET_VDEV(&dva[0], vd->vdev_id);
8922 DVA_SET_OFFSET(&dva[0], offset);
8923 DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
8924 DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
8926 BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
8928 BP_SET_LSIZE(bp, lsize);
8929 BP_SET_PSIZE(bp, psize);
8930 BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
8931 BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
8932 BP_SET_TYPE(bp, DMU_OT_NONE);
8933 BP_SET_LEVEL(bp, 0);
8934 BP_SET_DEDUP(bp, 0);
8935 BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
8937 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8938 zio = zio_root(spa, NULL, NULL, 0);
8940 if (vd == vd->vdev_top) {
8942 * Treat this as a normal block read.
8944 zio_nowait(zio_read(zio, spa, bp, pabd, psize, NULL, NULL,
8945 ZIO_PRIORITY_SYNC_READ,
8946 ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
8947 } else {
8949 * Treat this as a vdev child I/O.
8951 zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pabd,
8952 psize, ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
8953 ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
8954 ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW | ZIO_FLAG_OPTIONAL,
8955 NULL, NULL));
8958 error = zio_wait(zio);
8959 spa_config_exit(spa, SCL_STATE, FTAG);
8961 if (error) {
8962 (void) printf("Read of %s failed, error: %d\n", thing, error);
8963 goto out;
8966 uint64_t orig_lsize = lsize;
8967 buf = lbuf;
8968 if (flags & ZDB_FLAG_DECOMPRESS) {
8969 lsize = zdb_decompress_block(pabd, buf, lbuf,
8970 lsize, psize, flags);
8971 if (lsize == -1) {
8972 (void) printf("Decompress of %s failed\n", thing);
8973 goto out;
8975 } else {
8976 buf = abd_borrow_buf_copy(pabd, lsize);
8977 borrowed = B_TRUE;
8980 * Try to detect invalid block pointer. If invalid, try
8981 * decompressing.
8983 if ((flags & ZDB_FLAG_PRINT_BLKPTR || flags & ZDB_FLAG_INDIRECT) &&
8984 !(flags & ZDB_FLAG_DECOMPRESS)) {
8985 const blkptr_t *b = (const blkptr_t *)(void *)
8986 ((uintptr_t)buf + (uintptr_t)blkptr_offset);
8987 if (zfs_blkptr_verify(spa, b,
8988 BLK_CONFIG_NEEDED, BLK_VERIFY_ONLY) == B_FALSE) {
8989 abd_return_buf_copy(pabd, buf, lsize);
8990 borrowed = B_FALSE;
8991 buf = lbuf;
8992 lsize = zdb_decompress_block(pabd, buf,
8993 lbuf, lsize, psize, flags);
8994 b = (const blkptr_t *)(void *)
8995 ((uintptr_t)buf + (uintptr_t)blkptr_offset);
8996 if (lsize == -1 || zfs_blkptr_verify(spa, b,
8997 BLK_CONFIG_NEEDED, BLK_VERIFY_LOG) == B_FALSE) {
8998 printf("invalid block pointer at this DVA\n");
8999 goto out;
9004 if (flags & ZDB_FLAG_PRINT_BLKPTR)
9005 zdb_print_blkptr((blkptr_t *)(void *)
9006 ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
9007 else if (flags & ZDB_FLAG_RAW)
9008 zdb_dump_block_raw(buf, lsize, flags);
9009 else if (flags & ZDB_FLAG_INDIRECT)
9010 zdb_dump_indirect((blkptr_t *)buf,
9011 orig_lsize / sizeof (blkptr_t), flags);
9012 else if (flags & ZDB_FLAG_GBH)
9013 zdb_dump_gbh(buf, flags);
9014 else
9015 zdb_dump_block(thing, buf, lsize, flags);
9018 * If :c was specified, iterate through the checksum table to
9019 * calculate and display each checksum for our specified
9020 * DVA and length.
9022 if ((flags & ZDB_FLAG_CHECKSUM) && !(flags & ZDB_FLAG_RAW) &&
9023 !(flags & ZDB_FLAG_GBH)) {
9024 zio_t *czio;
9025 (void) printf("\n");
9026 for (enum zio_checksum ck = ZIO_CHECKSUM_LABEL;
9027 ck < ZIO_CHECKSUM_FUNCTIONS; ck++) {
9029 if ((zio_checksum_table[ck].ci_flags &
9030 ZCHECKSUM_FLAG_EMBEDDED) ||
9031 ck == ZIO_CHECKSUM_NOPARITY) {
9032 continue;
9034 BP_SET_CHECKSUM(bp, ck);
9035 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
9036 czio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
9037 if (vd == vd->vdev_top) {
9038 zio_nowait(zio_read(czio, spa, bp, pabd, psize,
9039 NULL, NULL,
9040 ZIO_PRIORITY_SYNC_READ,
9041 ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW |
9042 ZIO_FLAG_DONT_RETRY, NULL));
9043 } else {
9044 zio_nowait(zio_vdev_child_io(czio, bp, vd,
9045 offset, pabd, psize, ZIO_TYPE_READ,
9046 ZIO_PRIORITY_SYNC_READ,
9047 ZIO_FLAG_DONT_PROPAGATE |
9048 ZIO_FLAG_DONT_RETRY |
9049 ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW |
9050 ZIO_FLAG_SPECULATIVE |
9051 ZIO_FLAG_OPTIONAL, NULL, NULL));
9053 error = zio_wait(czio);
9054 if (error == 0 || error == ECKSUM) {
9055 zio_t *ck_zio = zio_null(NULL, spa, NULL,
9056 NULL, NULL, 0);
9057 ck_zio->io_offset =
9058 DVA_GET_OFFSET(&bp->blk_dva[0]);
9059 ck_zio->io_bp = bp;
9060 zio_checksum_compute(ck_zio, ck, pabd, lsize);
9061 printf(
9062 "%12s\t"
9063 "cksum=%016llx:%016llx:%016llx:%016llx\n",
9064 zio_checksum_table[ck].ci_name,
9065 (u_longlong_t)bp->blk_cksum.zc_word[0],
9066 (u_longlong_t)bp->blk_cksum.zc_word[1],
9067 (u_longlong_t)bp->blk_cksum.zc_word[2],
9068 (u_longlong_t)bp->blk_cksum.zc_word[3]);
9069 zio_wait(ck_zio);
9070 } else {
9071 printf("error %d reading block\n", error);
9073 spa_config_exit(spa, SCL_STATE, FTAG);
9077 if (borrowed)
9078 abd_return_buf_copy(pabd, buf, lsize);
9080 out:
9081 abd_free(pabd);
9082 umem_free(lbuf, SPA_MAXBLOCKSIZE);
9083 done:
9084 free(flagstr);
9085 free(dup);
9088 static void
9089 zdb_embedded_block(char *thing)
9091 blkptr_t bp = {{{{0}}}};
9092 unsigned long long *words = (void *)&bp;
9093 char *buf;
9094 int err;
9096 err = sscanf(thing, "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx:"
9097 "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx",
9098 words + 0, words + 1, words + 2, words + 3,
9099 words + 4, words + 5, words + 6, words + 7,
9100 words + 8, words + 9, words + 10, words + 11,
9101 words + 12, words + 13, words + 14, words + 15);
9102 if (err != 16) {
9103 (void) fprintf(stderr, "invalid input format\n");
9104 zdb_exit(1);
9106 ASSERT3U(BPE_GET_LSIZE(&bp), <=, SPA_MAXBLOCKSIZE);
9107 buf = malloc(SPA_MAXBLOCKSIZE);
9108 if (buf == NULL) {
9109 (void) fprintf(stderr, "out of memory\n");
9110 zdb_exit(1);
9112 err = decode_embedded_bp(&bp, buf, BPE_GET_LSIZE(&bp));
9113 if (err != 0) {
9114 (void) fprintf(stderr, "decode failed: %u\n", err);
9115 zdb_exit(1);
9117 zdb_dump_block_raw(buf, BPE_GET_LSIZE(&bp), 0);
9118 free(buf);
9121 /* check for valid hex or decimal numeric string */
9122 static boolean_t
9123 zdb_numeric(char *str)
9125 int i = 0, len;
9127 len = strlen(str);
9128 if (len == 0)
9129 return (B_FALSE);
9130 if (strncmp(str, "0x", 2) == 0 || strncmp(str, "0X", 2) == 0)
9131 i = 2;
9132 for (; i < len; i++) {
9133 if (!isxdigit(str[i]))
9134 return (B_FALSE);
9136 return (B_TRUE);
9139 static int
9140 dummy_get_file_info(dmu_object_type_t bonustype, const void *data,
9141 zfs_file_info_t *zoi)
9143 (void) data, (void) zoi;
9145 if (bonustype != DMU_OT_ZNODE && bonustype != DMU_OT_SA)
9146 return (ENOENT);
9148 (void) fprintf(stderr, "dummy_get_file_info: not implemented");
9149 abort();
9153 main(int argc, char **argv)
9155 int c;
9156 int dump_all = 1;
9157 int verbose = 0;
9158 int error = 0;
9159 char **searchdirs = NULL;
9160 int nsearch = 0;
9161 char *target, *target_pool, dsname[ZFS_MAX_DATASET_NAME_LEN];
9162 nvlist_t *policy = NULL;
9163 uint64_t max_txg = UINT64_MAX;
9164 int64_t objset_id = -1;
9165 uint64_t object;
9166 int flags = ZFS_IMPORT_MISSING_LOG;
9167 int rewind = ZPOOL_NEVER_REWIND;
9168 char *spa_config_path_env, *objset_str;
9169 boolean_t target_is_spa = B_TRUE, dataset_lookup = B_FALSE;
9170 nvlist_t *cfg = NULL;
9171 struct sigaction action;
9172 boolean_t force_import = B_FALSE;
9173 boolean_t config_path_console = B_FALSE;
9174 char pbuf[MAXPATHLEN];
9176 dprintf_setup(&argc, argv);
9179 * Set up signal handlers, so if we crash due to bad on-disk data we
9180 * can get more info. Unlike ztest, we don't bail out if we can't set
9181 * up signal handlers, because zdb is very useful without them.
9183 action.sa_handler = sig_handler;
9184 sigemptyset(&action.sa_mask);
9185 action.sa_flags = 0;
9186 if (sigaction(SIGSEGV, &action, NULL) < 0) {
9187 (void) fprintf(stderr, "zdb: cannot catch SIGSEGV: %s\n",
9188 strerror(errno));
9190 if (sigaction(SIGABRT, &action, NULL) < 0) {
9191 (void) fprintf(stderr, "zdb: cannot catch SIGABRT: %s\n",
9192 strerror(errno));
9196 * If there is an environment variable SPA_CONFIG_PATH it overrides
9197 * default spa_config_path setting. If -U flag is specified it will
9198 * override this environment variable settings once again.
9200 spa_config_path_env = getenv("SPA_CONFIG_PATH");
9201 if (spa_config_path_env != NULL)
9202 spa_config_path = spa_config_path_env;
9205 * For performance reasons, we set this tunable down. We do so before
9206 * the arg parsing section so that the user can override this value if
9207 * they choose.
9209 zfs_btree_verify_intensity = 3;
9211 struct option long_options[] = {
9212 {"ignore-assertions", no_argument, NULL, 'A'},
9213 {"block-stats", no_argument, NULL, 'b'},
9214 {"backup", no_argument, NULL, 'B'},
9215 {"checksum", no_argument, NULL, 'c'},
9216 {"config", no_argument, NULL, 'C'},
9217 {"datasets", no_argument, NULL, 'd'},
9218 {"dedup-stats", no_argument, NULL, 'D'},
9219 {"exported", no_argument, NULL, 'e'},
9220 {"embedded-block-pointer", no_argument, NULL, 'E'},
9221 {"automatic-rewind", no_argument, NULL, 'F'},
9222 {"dump-debug-msg", no_argument, NULL, 'G'},
9223 {"history", no_argument, NULL, 'h'},
9224 {"intent-logs", no_argument, NULL, 'i'},
9225 {"inflight", required_argument, NULL, 'I'},
9226 {"checkpointed-state", no_argument, NULL, 'k'},
9227 {"key", required_argument, NULL, 'K'},
9228 {"label", no_argument, NULL, 'l'},
9229 {"disable-leak-tracking", no_argument, NULL, 'L'},
9230 {"metaslabs", no_argument, NULL, 'm'},
9231 {"metaslab-groups", no_argument, NULL, 'M'},
9232 {"numeric", no_argument, NULL, 'N'},
9233 {"option", required_argument, NULL, 'o'},
9234 {"object-lookups", no_argument, NULL, 'O'},
9235 {"path", required_argument, NULL, 'p'},
9236 {"parseable", no_argument, NULL, 'P'},
9237 {"skip-label", no_argument, NULL, 'q'},
9238 {"copy-object", no_argument, NULL, 'r'},
9239 {"read-block", no_argument, NULL, 'R'},
9240 {"io-stats", no_argument, NULL, 's'},
9241 {"simulate-dedup", no_argument, NULL, 'S'},
9242 {"txg", required_argument, NULL, 't'},
9243 {"brt-stats", no_argument, NULL, 'T'},
9244 {"uberblock", no_argument, NULL, 'u'},
9245 {"cachefile", required_argument, NULL, 'U'},
9246 {"verbose", no_argument, NULL, 'v'},
9247 {"verbatim", no_argument, NULL, 'V'},
9248 {"dump-blocks", required_argument, NULL, 'x'},
9249 {"extreme-rewind", no_argument, NULL, 'X'},
9250 {"all-reconstruction", no_argument, NULL, 'Y'},
9251 {"livelist", no_argument, NULL, 'y'},
9252 {"zstd-headers", no_argument, NULL, 'Z'},
9253 {0, 0, 0, 0}
9256 while ((c = getopt_long(argc, argv,
9257 "AbBcCdDeEFGhiI:kK:lLmMNo:Op:PqrRsSt:TuU:vVx:XYyZ",
9258 long_options, NULL)) != -1) {
9259 switch (c) {
9260 case 'b':
9261 case 'B':
9262 case 'c':
9263 case 'C':
9264 case 'd':
9265 case 'D':
9266 case 'E':
9267 case 'G':
9268 case 'h':
9269 case 'i':
9270 case 'l':
9271 case 'm':
9272 case 'M':
9273 case 'N':
9274 case 'O':
9275 case 'r':
9276 case 'R':
9277 case 's':
9278 case 'S':
9279 case 'T':
9280 case 'u':
9281 case 'y':
9282 case 'Z':
9283 dump_opt[c]++;
9284 dump_all = 0;
9285 break;
9286 case 'A':
9287 case 'e':
9288 case 'F':
9289 case 'k':
9290 case 'L':
9291 case 'P':
9292 case 'q':
9293 case 'X':
9294 dump_opt[c]++;
9295 break;
9296 case 'Y':
9297 zfs_reconstruct_indirect_combinations_max = INT_MAX;
9298 zfs_deadman_enabled = 0;
9299 break;
9300 /* NB: Sort single match options below. */
9301 case 'I':
9302 max_inflight_bytes = strtoull(optarg, NULL, 0);
9303 if (max_inflight_bytes == 0) {
9304 (void) fprintf(stderr, "maximum number "
9305 "of inflight bytes must be greater "
9306 "than 0\n");
9307 usage();
9309 break;
9310 case 'K':
9311 dump_opt[c]++;
9312 key_material = strdup(optarg);
9313 /* redact key material in process table */
9314 while (*optarg != '\0') { *optarg++ = '*'; }
9315 break;
9316 case 'o':
9317 error = set_global_var(optarg);
9318 if (error != 0)
9319 usage();
9320 break;
9321 case 'p':
9322 if (searchdirs == NULL) {
9323 searchdirs = umem_alloc(sizeof (char *),
9324 UMEM_NOFAIL);
9325 } else {
9326 char **tmp = umem_alloc((nsearch + 1) *
9327 sizeof (char *), UMEM_NOFAIL);
9328 memcpy(tmp, searchdirs, nsearch *
9329 sizeof (char *));
9330 umem_free(searchdirs,
9331 nsearch * sizeof (char *));
9332 searchdirs = tmp;
9334 searchdirs[nsearch++] = optarg;
9335 break;
9336 case 't':
9337 max_txg = strtoull(optarg, NULL, 0);
9338 if (max_txg < TXG_INITIAL) {
9339 (void) fprintf(stderr, "incorrect txg "
9340 "specified: %s\n", optarg);
9341 usage();
9343 break;
9344 case 'U':
9345 config_path_console = B_TRUE;
9346 spa_config_path = optarg;
9347 if (spa_config_path[0] != '/') {
9348 (void) fprintf(stderr,
9349 "cachefile must be an absolute path "
9350 "(i.e. start with a slash)\n");
9351 usage();
9353 break;
9354 case 'v':
9355 verbose++;
9356 break;
9357 case 'V':
9358 flags = ZFS_IMPORT_VERBATIM;
9359 break;
9360 case 'x':
9361 vn_dumpdir = optarg;
9362 break;
9363 default:
9364 usage();
9365 break;
9369 if (!dump_opt['e'] && searchdirs != NULL) {
9370 (void) fprintf(stderr, "-p option requires use of -e\n");
9371 usage();
9373 #if defined(_LP64)
9375 * ZDB does not typically re-read blocks; therefore limit the ARC
9376 * to 256 MB, which can be used entirely for metadata.
9378 zfs_arc_min = 2ULL << SPA_MAXBLOCKSHIFT;
9379 zfs_arc_max = 256 * 1024 * 1024;
9380 #endif
9383 * "zdb -c" uses checksum-verifying scrub i/os which are async reads.
9384 * "zdb -b" uses traversal prefetch which uses async reads.
9385 * For good performance, let several of them be active at once.
9387 zfs_vdev_async_read_max_active = 10;
9390 * Disable reference tracking for better performance.
9392 reference_tracking_enable = B_FALSE;
9395 * Do not fail spa_load when spa_load_verify fails. This is needed
9396 * to load non-idle pools.
9398 spa_load_verify_dryrun = B_TRUE;
9401 * ZDB should have ability to read spacemaps.
9403 spa_mode_readable_spacemaps = B_TRUE;
9405 if (dump_all)
9406 verbose = MAX(verbose, 1);
9408 for (c = 0; c < 256; c++) {
9409 if (dump_all && strchr("ABeEFkKlLNOPrRSXy", c) == NULL)
9410 dump_opt[c] = 1;
9411 if (dump_opt[c])
9412 dump_opt[c] += verbose;
9415 libspl_set_assert_ok((dump_opt['A'] == 1) || (dump_opt['A'] > 2));
9416 zfs_recover = (dump_opt['A'] > 1);
9418 argc -= optind;
9419 argv += optind;
9420 if (argc < 2 && dump_opt['R'])
9421 usage();
9423 target = argv[0];
9426 * Automate cachefile
9428 if (!spa_config_path_env && !config_path_console && target &&
9429 libzfs_core_init() == 0) {
9430 char *pname = strdup(target);
9431 const char *value;
9432 nvlist_t *pnvl = NULL;
9433 nvlist_t *vnvl = NULL;
9435 if (strpbrk(pname, "/@") != NULL)
9436 *strpbrk(pname, "/@") = '\0';
9438 if (pname && lzc_get_props(pname, &pnvl) == 0) {
9439 if (nvlist_lookup_nvlist(pnvl, "cachefile",
9440 &vnvl) == 0) {
9441 value = fnvlist_lookup_string(vnvl,
9442 ZPROP_VALUE);
9443 } else {
9444 value = "-";
9446 strlcpy(pbuf, value, sizeof (pbuf));
9447 if (pbuf[0] != '\0') {
9448 if (pbuf[0] == '/') {
9449 if (access(pbuf, F_OK) == 0)
9450 spa_config_path = pbuf;
9451 else
9452 force_import = B_TRUE;
9453 } else if ((strcmp(pbuf, "-") == 0 &&
9454 access(ZPOOL_CACHE, F_OK) != 0) ||
9455 strcmp(pbuf, "none") == 0) {
9456 force_import = B_TRUE;
9459 nvlist_free(vnvl);
9462 free(pname);
9463 nvlist_free(pnvl);
9464 libzfs_core_fini();
9467 dmu_objset_register_type(DMU_OST_ZFS, dummy_get_file_info);
9468 kernel_init(SPA_MODE_READ);
9469 kernel_init_done = B_TRUE;
9471 if (dump_opt['E']) {
9472 if (argc != 1)
9473 usage();
9474 zdb_embedded_block(argv[0]);
9475 error = 0;
9476 goto fini;
9479 if (argc < 1) {
9480 if (!dump_opt['e'] && dump_opt['C']) {
9481 dump_cachefile(spa_config_path);
9482 error = 0;
9483 goto fini;
9485 usage();
9488 if (dump_opt['l']) {
9489 error = dump_label(argv[0]);
9490 goto fini;
9493 if (dump_opt['X'] || dump_opt['F'])
9494 rewind = ZPOOL_DO_REWIND |
9495 (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
9497 /* -N implies -d */
9498 if (dump_opt['N'] && dump_opt['d'] == 0)
9499 dump_opt['d'] = dump_opt['N'];
9501 if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
9502 nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, max_txg) != 0 ||
9503 nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY, rewind) != 0)
9504 fatal("internal error: %s", strerror(ENOMEM));
9506 error = 0;
9508 if (strpbrk(target, "/@") != NULL) {
9509 size_t targetlen;
9511 target_pool = strdup(target);
9512 *strpbrk(target_pool, "/@") = '\0';
9514 target_is_spa = B_FALSE;
9515 targetlen = strlen(target);
9516 if (targetlen && target[targetlen - 1] == '/')
9517 target[targetlen - 1] = '\0';
9520 * See if an objset ID was supplied (-d <pool>/<objset ID>).
9521 * To disambiguate tank/100, consider the 100 as objsetID
9522 * if -N was given, otherwise 100 is an objsetID iff
9523 * tank/100 as a named dataset fails on lookup.
9525 objset_str = strchr(target, '/');
9526 if (objset_str && strlen(objset_str) > 1 &&
9527 zdb_numeric(objset_str + 1)) {
9528 char *endptr;
9529 errno = 0;
9530 objset_str++;
9531 objset_id = strtoull(objset_str, &endptr, 0);
9532 /* dataset 0 is the same as opening the pool */
9533 if (errno == 0 && endptr != objset_str &&
9534 objset_id != 0) {
9535 if (dump_opt['N'])
9536 dataset_lookup = B_TRUE;
9538 /* normal dataset name not an objset ID */
9539 if (endptr == objset_str) {
9540 objset_id = -1;
9542 } else if (objset_str && !zdb_numeric(objset_str + 1) &&
9543 dump_opt['N']) {
9544 printf("Supply a numeric objset ID with -N\n");
9545 error = 1;
9546 goto fini;
9548 } else {
9549 target_pool = target;
9552 if (dump_opt['e'] || force_import) {
9553 importargs_t args = { 0 };
9556 * If path is not provided, search in /dev
9558 if (searchdirs == NULL) {
9559 searchdirs = umem_alloc(sizeof (char *), UMEM_NOFAIL);
9560 searchdirs[nsearch++] = (char *)ZFS_DEVDIR;
9563 args.paths = nsearch;
9564 args.path = searchdirs;
9565 args.can_be_active = B_TRUE;
9567 libpc_handle_t lpch = {
9568 .lpc_lib_handle = NULL,
9569 .lpc_ops = &libzpool_config_ops,
9570 .lpc_printerr = B_TRUE
9572 error = zpool_find_config(&lpch, target_pool, &cfg, &args);
9574 if (error == 0) {
9576 if (nvlist_add_nvlist(cfg,
9577 ZPOOL_LOAD_POLICY, policy) != 0) {
9578 fatal("can't open '%s': %s",
9579 target, strerror(ENOMEM));
9582 if (dump_opt['C'] > 1) {
9583 (void) printf("\nConfiguration for import:\n");
9584 dump_nvlist(cfg, 8);
9588 * Disable the activity check to allow examination of
9589 * active pools.
9591 error = spa_import(target_pool, cfg, NULL,
9592 flags | ZFS_IMPORT_SKIP_MMP);
9596 if (searchdirs != NULL) {
9597 umem_free(searchdirs, nsearch * sizeof (char *));
9598 searchdirs = NULL;
9602 * We need to make sure to process -O option or call
9603 * dump_path after the -e option has been processed,
9604 * which imports the pool to the namespace if it's
9605 * not in the cachefile.
9607 if (dump_opt['O']) {
9608 if (argc != 2)
9609 usage();
9610 dump_opt['v'] = verbose + 3;
9611 error = dump_path(argv[0], argv[1], NULL);
9612 goto fini;
9615 if (dump_opt['r']) {
9616 target_is_spa = B_FALSE;
9617 if (argc != 3)
9618 usage();
9619 dump_opt['v'] = verbose;
9620 error = dump_path(argv[0], argv[1], &object);
9621 if (error != 0)
9622 fatal("internal error: %s", strerror(error));
9626 * import_checkpointed_state makes the assumption that the
9627 * target pool that we pass it is already part of the spa
9628 * namespace. Because of that we need to make sure to call
9629 * it always after the -e option has been processed, which
9630 * imports the pool to the namespace if it's not in the
9631 * cachefile.
9633 char *checkpoint_pool = NULL;
9634 char *checkpoint_target = NULL;
9635 if (dump_opt['k']) {
9636 checkpoint_pool = import_checkpointed_state(target, cfg,
9637 &checkpoint_target);
9639 if (checkpoint_target != NULL)
9640 target = checkpoint_target;
9643 if (cfg != NULL) {
9644 nvlist_free(cfg);
9645 cfg = NULL;
9648 if (target_pool != target)
9649 free(target_pool);
9651 if (error == 0) {
9652 if (dump_opt['k'] && (target_is_spa || dump_opt['R'])) {
9653 ASSERT(checkpoint_pool != NULL);
9654 ASSERT(checkpoint_target == NULL);
9656 error = spa_open(checkpoint_pool, &spa, FTAG);
9657 if (error != 0) {
9658 fatal("Tried to open pool \"%s\" but "
9659 "spa_open() failed with error %d\n",
9660 checkpoint_pool, error);
9663 } else if (target_is_spa || dump_opt['R'] || dump_opt['B'] ||
9664 objset_id == 0) {
9665 zdb_set_skip_mmp(target);
9666 error = spa_open_rewind(target, &spa, FTAG, policy,
9667 NULL);
9668 if (error) {
9670 * If we're missing the log device then
9671 * try opening the pool after clearing the
9672 * log state.
9674 mutex_enter(&spa_namespace_lock);
9675 if ((spa = spa_lookup(target)) != NULL &&
9676 spa->spa_log_state == SPA_LOG_MISSING) {
9677 spa->spa_log_state = SPA_LOG_CLEAR;
9678 error = 0;
9680 mutex_exit(&spa_namespace_lock);
9682 if (!error) {
9683 error = spa_open_rewind(target, &spa,
9684 FTAG, policy, NULL);
9687 } else if (strpbrk(target, "#") != NULL) {
9688 dsl_pool_t *dp;
9689 error = dsl_pool_hold(target, FTAG, &dp);
9690 if (error != 0) {
9691 fatal("can't dump '%s': %s", target,
9692 strerror(error));
9694 error = dump_bookmark(dp, target, B_TRUE, verbose > 1);
9695 dsl_pool_rele(dp, FTAG);
9696 if (error != 0) {
9697 fatal("can't dump '%s': %s", target,
9698 strerror(error));
9700 goto fini;
9701 } else {
9702 target_pool = strdup(target);
9703 if (strpbrk(target, "/@") != NULL)
9704 *strpbrk(target_pool, "/@") = '\0';
9706 zdb_set_skip_mmp(target);
9708 * If -N was supplied, the user has indicated that
9709 * zdb -d <pool>/<objsetID> is in effect. Otherwise
9710 * we first assume that the dataset string is the
9711 * dataset name. If dmu_objset_hold fails with the
9712 * dataset string, and we have an objset_id, retry the
9713 * lookup with the objsetID.
9715 boolean_t retry = B_TRUE;
9716 retry_lookup:
9717 if (dataset_lookup == B_TRUE) {
9719 * Use the supplied id to get the name
9720 * for open_objset.
9722 error = spa_open(target_pool, &spa, FTAG);
9723 if (error == 0) {
9724 error = name_from_objset_id(spa,
9725 objset_id, dsname);
9726 spa_close(spa, FTAG);
9727 if (error == 0)
9728 target = dsname;
9731 if (error == 0) {
9732 if (objset_id > 0 && retry) {
9733 int err = dmu_objset_hold(target, FTAG,
9734 &os);
9735 if (err) {
9736 dataset_lookup = B_TRUE;
9737 retry = B_FALSE;
9738 goto retry_lookup;
9739 } else {
9740 dmu_objset_rele(os, FTAG);
9743 error = open_objset(target, FTAG, &os);
9745 if (error == 0)
9746 spa = dmu_objset_spa(os);
9747 free(target_pool);
9750 nvlist_free(policy);
9752 if (error)
9753 fatal("can't open '%s': %s", target, strerror(error));
9756 * Set the pool failure mode to panic in order to prevent the pool
9757 * from suspending. A suspended I/O will have no way to resume and
9758 * can prevent the zdb(8) command from terminating as expected.
9760 if (spa != NULL)
9761 spa->spa_failmode = ZIO_FAILURE_MODE_PANIC;
9763 argv++;
9764 argc--;
9765 if (dump_opt['r']) {
9766 error = zdb_copy_object(os, object, argv[1]);
9767 } else if (!dump_opt['R']) {
9768 flagbits['d'] = ZOR_FLAG_DIRECTORY;
9769 flagbits['f'] = ZOR_FLAG_PLAIN_FILE;
9770 flagbits['m'] = ZOR_FLAG_SPACE_MAP;
9771 flagbits['z'] = ZOR_FLAG_ZAP;
9772 flagbits['A'] = ZOR_FLAG_ALL_TYPES;
9774 if (argc > 0 && dump_opt['d']) {
9775 zopt_object_args = argc;
9776 zopt_object_ranges = calloc(zopt_object_args,
9777 sizeof (zopt_object_range_t));
9778 for (unsigned i = 0; i < zopt_object_args; i++) {
9779 int err;
9780 const char *msg = NULL;
9782 err = parse_object_range(argv[i],
9783 &zopt_object_ranges[i], &msg);
9784 if (err != 0)
9785 fatal("Bad object or range: '%s': %s\n",
9786 argv[i], msg ?: "");
9788 } else if (argc > 0 && dump_opt['m']) {
9789 zopt_metaslab_args = argc;
9790 zopt_metaslab = calloc(zopt_metaslab_args,
9791 sizeof (uint64_t));
9792 for (unsigned i = 0; i < zopt_metaslab_args; i++) {
9793 errno = 0;
9794 zopt_metaslab[i] = strtoull(argv[i], NULL, 0);
9795 if (zopt_metaslab[i] == 0 && errno != 0)
9796 fatal("bad number %s: %s", argv[i],
9797 strerror(errno));
9800 if (dump_opt['B']) {
9801 dump_backup(target, objset_id,
9802 argc > 0 ? argv[0] : NULL);
9803 } else if (os != NULL) {
9804 dump_objset(os);
9805 } else if (zopt_object_args > 0 && !dump_opt['m']) {
9806 dump_objset(spa->spa_meta_objset);
9807 } else {
9808 dump_zpool(spa);
9810 } else {
9811 flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
9812 flagbits['c'] = ZDB_FLAG_CHECKSUM;
9813 flagbits['d'] = ZDB_FLAG_DECOMPRESS;
9814 flagbits['e'] = ZDB_FLAG_BSWAP;
9815 flagbits['g'] = ZDB_FLAG_GBH;
9816 flagbits['i'] = ZDB_FLAG_INDIRECT;
9817 flagbits['r'] = ZDB_FLAG_RAW;
9818 flagbits['v'] = ZDB_FLAG_VERBOSE;
9820 for (int i = 0; i < argc; i++)
9821 zdb_read_block(argv[i], spa);
9824 if (dump_opt['k']) {
9825 free(checkpoint_pool);
9826 if (!target_is_spa)
9827 free(checkpoint_target);
9830 fini:
9831 if (spa != NULL)
9832 zdb_ddt_cleanup(spa);
9834 if (os != NULL) {
9835 close_objset(os, FTAG);
9836 } else if (spa != NULL) {
9837 spa_close(spa, FTAG);
9840 fuid_table_destroy();
9842 dump_debug_buffer();
9844 if (kernel_init_done)
9845 kernel_fini();
9847 return (error);