zdb: fix printf() length for uint64_t devid
[zfs.git] / cmd / zdb / zdb.c
blob3fc9fd2a9d814c4a471991f9e1888a06b53fe9f1
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, 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/fs/zfs.h>
52 #include <sys/zfs_znode.h>
53 #include <sys/zfs_sa.h>
54 #include <sys/sa.h>
55 #include <sys/sa_impl.h>
56 #include <sys/vdev.h>
57 #include <sys/vdev_impl.h>
58 #include <sys/metaslab_impl.h>
59 #include <sys/dmu_objset.h>
60 #include <sys/dsl_dir.h>
61 #include <sys/dsl_dataset.h>
62 #include <sys/dsl_pool.h>
63 #include <sys/dsl_bookmark.h>
64 #include <sys/dbuf.h>
65 #include <sys/zil.h>
66 #include <sys/zil_impl.h>
67 #include <sys/stat.h>
68 #include <sys/resource.h>
69 #include <sys/dmu_send.h>
70 #include <sys/dmu_traverse.h>
71 #include <sys/zio_checksum.h>
72 #include <sys/zio_compress.h>
73 #include <sys/zfs_fuid.h>
74 #include <sys/arc.h>
75 #include <sys/arc_impl.h>
76 #include <sys/ddt.h>
77 #include <sys/zfeature.h>
78 #include <sys/abd.h>
79 #include <sys/blkptr.h>
80 #include <sys/dsl_crypt.h>
81 #include <sys/dsl_scan.h>
82 #include <sys/btree.h>
83 #include <sys/brt.h>
84 #include <sys/brt_impl.h>
85 #include <zfs_comutil.h>
86 #include <sys/zstd/zstd.h>
88 #include <libnvpair.h>
89 #include <libzutil.h>
91 #include "zdb.h"
93 #define ZDB_COMPRESS_NAME(idx) ((idx) < ZIO_COMPRESS_FUNCTIONS ? \
94 zio_compress_table[(idx)].ci_name : "UNKNOWN")
95 #define ZDB_CHECKSUM_NAME(idx) ((idx) < ZIO_CHECKSUM_FUNCTIONS ? \
96 zio_checksum_table[(idx)].ci_name : "UNKNOWN")
97 #define ZDB_OT_TYPE(idx) ((idx) < DMU_OT_NUMTYPES ? (idx) : \
98 (idx) == DMU_OTN_ZAP_DATA || (idx) == DMU_OTN_ZAP_METADATA ? \
99 DMU_OT_ZAP_OTHER : \
100 (idx) == DMU_OTN_UINT64_DATA || (idx) == DMU_OTN_UINT64_METADATA ? \
101 DMU_OT_UINT64_OTHER : DMU_OT_NUMTYPES)
103 /* Some platforms require part of inode IDs to be remapped */
104 #ifdef __APPLE__
105 #define ZDB_MAP_OBJECT_ID(obj) INO_XNUTOZFS(obj, 2)
106 #else
107 #define ZDB_MAP_OBJECT_ID(obj) (obj)
108 #endif
110 static const char *
111 zdb_ot_name(dmu_object_type_t type)
113 if (type < DMU_OT_NUMTYPES)
114 return (dmu_ot[type].ot_name);
115 else if ((type & DMU_OT_NEWTYPE) &&
116 ((type & DMU_OT_BYTESWAP_MASK) < DMU_BSWAP_NUMFUNCS))
117 return (dmu_ot_byteswap[type & DMU_OT_BYTESWAP_MASK].ob_name);
118 else
119 return ("UNKNOWN");
122 extern int reference_tracking_enable;
123 extern int zfs_recover;
124 extern uint_t zfs_vdev_async_read_max_active;
125 extern boolean_t spa_load_verify_dryrun;
126 extern boolean_t spa_mode_readable_spacemaps;
127 extern uint_t zfs_reconstruct_indirect_combinations_max;
128 extern uint_t zfs_btree_verify_intensity;
130 static const char cmdname[] = "zdb";
131 uint8_t dump_opt[256];
133 typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
135 static uint64_t *zopt_metaslab = NULL;
136 static unsigned zopt_metaslab_args = 0;
138 typedef struct zopt_object_range {
139 uint64_t zor_obj_start;
140 uint64_t zor_obj_end;
141 uint64_t zor_flags;
142 } zopt_object_range_t;
144 static zopt_object_range_t *zopt_object_ranges = NULL;
145 static unsigned zopt_object_args = 0;
147 static int flagbits[256];
149 #define ZOR_FLAG_PLAIN_FILE 0x0001
150 #define ZOR_FLAG_DIRECTORY 0x0002
151 #define ZOR_FLAG_SPACE_MAP 0x0004
152 #define ZOR_FLAG_ZAP 0x0008
153 #define ZOR_FLAG_ALL_TYPES -1
154 #define ZOR_SUPPORTED_FLAGS (ZOR_FLAG_PLAIN_FILE | \
155 ZOR_FLAG_DIRECTORY | \
156 ZOR_FLAG_SPACE_MAP | \
157 ZOR_FLAG_ZAP)
159 #define ZDB_FLAG_CHECKSUM 0x0001
160 #define ZDB_FLAG_DECOMPRESS 0x0002
161 #define ZDB_FLAG_BSWAP 0x0004
162 #define ZDB_FLAG_GBH 0x0008
163 #define ZDB_FLAG_INDIRECT 0x0010
164 #define ZDB_FLAG_RAW 0x0020
165 #define ZDB_FLAG_PRINT_BLKPTR 0x0040
166 #define ZDB_FLAG_VERBOSE 0x0080
168 static uint64_t max_inflight_bytes = 256 * 1024 * 1024; /* 256MB */
169 static int leaked_objects = 0;
170 static range_tree_t *mos_refd_objs;
172 static void snprintf_blkptr_compact(char *, size_t, const blkptr_t *,
173 boolean_t);
174 static void mos_obj_refd(uint64_t);
175 static void mos_obj_refd_multiple(uint64_t);
176 static int dump_bpobj_cb(void *arg, const blkptr_t *bp, boolean_t free,
177 dmu_tx_t *tx);
179 typedef struct sublivelist_verify {
180 /* FREE's that haven't yet matched to an ALLOC, in one sub-livelist */
181 zfs_btree_t sv_pair;
183 /* ALLOC's without a matching FREE, accumulates across sub-livelists */
184 zfs_btree_t sv_leftover;
185 } sublivelist_verify_t;
187 static int
188 livelist_compare(const void *larg, const void *rarg)
190 const blkptr_t *l = larg;
191 const blkptr_t *r = rarg;
193 /* Sort them according to dva[0] */
194 uint64_t l_dva0_vdev, r_dva0_vdev;
195 l_dva0_vdev = DVA_GET_VDEV(&l->blk_dva[0]);
196 r_dva0_vdev = DVA_GET_VDEV(&r->blk_dva[0]);
197 if (l_dva0_vdev < r_dva0_vdev)
198 return (-1);
199 else if (l_dva0_vdev > r_dva0_vdev)
200 return (+1);
202 /* if vdevs are equal, sort by offsets. */
203 uint64_t l_dva0_offset;
204 uint64_t r_dva0_offset;
205 l_dva0_offset = DVA_GET_OFFSET(&l->blk_dva[0]);
206 r_dva0_offset = DVA_GET_OFFSET(&r->blk_dva[0]);
207 if (l_dva0_offset < r_dva0_offset) {
208 return (-1);
209 } else if (l_dva0_offset > r_dva0_offset) {
210 return (+1);
214 * Since we're storing blkptrs without cancelling FREE/ALLOC pairs,
215 * it's possible the offsets are equal. In that case, sort by txg
217 if (l->blk_birth < r->blk_birth) {
218 return (-1);
219 } else if (l->blk_birth > r->blk_birth) {
220 return (+1);
222 return (0);
225 typedef struct sublivelist_verify_block {
226 dva_t svb_dva;
229 * We need this to check if the block marked as allocated
230 * in the livelist was freed (and potentially reallocated)
231 * in the metaslab spacemaps at a later TXG.
233 uint64_t svb_allocated_txg;
234 } sublivelist_verify_block_t;
236 static void zdb_print_blkptr(const blkptr_t *bp, int flags);
238 typedef struct sublivelist_verify_block_refcnt {
239 /* block pointer entry in livelist being verified */
240 blkptr_t svbr_blk;
243 * Refcount gets incremented to 1 when we encounter the first
244 * FREE entry for the svfbr block pointer and a node for it
245 * is created in our ZDB verification/tracking metadata.
247 * As we encounter more FREE entries we increment this counter
248 * and similarly decrement it whenever we find the respective
249 * ALLOC entries for this block.
251 * When the refcount gets to 0 it means that all the FREE and
252 * ALLOC entries of this block have paired up and we no longer
253 * need to track it in our verification logic (e.g. the node
254 * containing this struct in our verification data structure
255 * should be freed).
257 * [refer to sublivelist_verify_blkptr() for the actual code]
259 uint32_t svbr_refcnt;
260 } sublivelist_verify_block_refcnt_t;
262 static int
263 sublivelist_block_refcnt_compare(const void *larg, const void *rarg)
265 const sublivelist_verify_block_refcnt_t *l = larg;
266 const sublivelist_verify_block_refcnt_t *r = rarg;
267 return (livelist_compare(&l->svbr_blk, &r->svbr_blk));
270 static int
271 sublivelist_verify_blkptr(void *arg, const blkptr_t *bp, boolean_t free,
272 dmu_tx_t *tx)
274 ASSERT3P(tx, ==, NULL);
275 struct sublivelist_verify *sv = arg;
276 sublivelist_verify_block_refcnt_t current = {
277 .svbr_blk = *bp,
280 * Start with 1 in case this is the first free entry.
281 * This field is not used for our B-Tree comparisons
282 * anyway.
284 .svbr_refcnt = 1,
287 zfs_btree_index_t where;
288 sublivelist_verify_block_refcnt_t *pair =
289 zfs_btree_find(&sv->sv_pair, &current, &where);
290 if (free) {
291 if (pair == NULL) {
292 /* first free entry for this block pointer */
293 zfs_btree_add(&sv->sv_pair, &current);
294 } else {
295 pair->svbr_refcnt++;
297 } else {
298 if (pair == NULL) {
299 /* block that is currently marked as allocated */
300 for (int i = 0; i < SPA_DVAS_PER_BP; i++) {
301 if (DVA_IS_EMPTY(&bp->blk_dva[i]))
302 break;
303 sublivelist_verify_block_t svb = {
304 .svb_dva = bp->blk_dva[i],
305 .svb_allocated_txg = bp->blk_birth
308 if (zfs_btree_find(&sv->sv_leftover, &svb,
309 &where) == NULL) {
310 zfs_btree_add_idx(&sv->sv_leftover,
311 &svb, &where);
314 } else {
315 /* alloc matches a free entry */
316 pair->svbr_refcnt--;
317 if (pair->svbr_refcnt == 0) {
318 /* all allocs and frees have been matched */
319 zfs_btree_remove_idx(&sv->sv_pair, &where);
324 return (0);
327 static int
328 sublivelist_verify_func(void *args, dsl_deadlist_entry_t *dle)
330 int err;
331 struct sublivelist_verify *sv = args;
333 zfs_btree_create(&sv->sv_pair, sublivelist_block_refcnt_compare, NULL,
334 sizeof (sublivelist_verify_block_refcnt_t));
336 err = bpobj_iterate_nofree(&dle->dle_bpobj, sublivelist_verify_blkptr,
337 sv, NULL);
339 sublivelist_verify_block_refcnt_t *e;
340 zfs_btree_index_t *cookie = NULL;
341 while ((e = zfs_btree_destroy_nodes(&sv->sv_pair, &cookie)) != NULL) {
342 char blkbuf[BP_SPRINTF_LEN];
343 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf),
344 &e->svbr_blk, B_TRUE);
345 (void) printf("\tERROR: %d unmatched FREE(s): %s\n",
346 e->svbr_refcnt, blkbuf);
348 zfs_btree_destroy(&sv->sv_pair);
350 return (err);
353 static int
354 livelist_block_compare(const void *larg, const void *rarg)
356 const sublivelist_verify_block_t *l = larg;
357 const sublivelist_verify_block_t *r = rarg;
359 if (DVA_GET_VDEV(&l->svb_dva) < DVA_GET_VDEV(&r->svb_dva))
360 return (-1);
361 else if (DVA_GET_VDEV(&l->svb_dva) > DVA_GET_VDEV(&r->svb_dva))
362 return (+1);
364 if (DVA_GET_OFFSET(&l->svb_dva) < DVA_GET_OFFSET(&r->svb_dva))
365 return (-1);
366 else if (DVA_GET_OFFSET(&l->svb_dva) > DVA_GET_OFFSET(&r->svb_dva))
367 return (+1);
369 if (DVA_GET_ASIZE(&l->svb_dva) < DVA_GET_ASIZE(&r->svb_dva))
370 return (-1);
371 else if (DVA_GET_ASIZE(&l->svb_dva) > DVA_GET_ASIZE(&r->svb_dva))
372 return (+1);
374 return (0);
378 * Check for errors in a livelist while tracking all unfreed ALLOCs in the
379 * sublivelist_verify_t: sv->sv_leftover
381 static void
382 livelist_verify(dsl_deadlist_t *dl, void *arg)
384 sublivelist_verify_t *sv = arg;
385 dsl_deadlist_iterate(dl, sublivelist_verify_func, sv);
389 * Check for errors in the livelist entry and discard the intermediary
390 * data structures
392 static int
393 sublivelist_verify_lightweight(void *args, dsl_deadlist_entry_t *dle)
395 (void) args;
396 sublivelist_verify_t sv;
397 zfs_btree_create(&sv.sv_leftover, livelist_block_compare, NULL,
398 sizeof (sublivelist_verify_block_t));
399 int err = sublivelist_verify_func(&sv, dle);
400 zfs_btree_clear(&sv.sv_leftover);
401 zfs_btree_destroy(&sv.sv_leftover);
402 return (err);
405 typedef struct metaslab_verify {
407 * Tree containing all the leftover ALLOCs from the livelists
408 * that are part of this metaslab.
410 zfs_btree_t mv_livelist_allocs;
413 * Metaslab information.
415 uint64_t mv_vdid;
416 uint64_t mv_msid;
417 uint64_t mv_start;
418 uint64_t mv_end;
421 * What's currently allocated for this metaslab.
423 range_tree_t *mv_allocated;
424 } metaslab_verify_t;
426 typedef void ll_iter_t(dsl_deadlist_t *ll, void *arg);
428 typedef int (*zdb_log_sm_cb_t)(spa_t *spa, space_map_entry_t *sme, uint64_t txg,
429 void *arg);
431 typedef struct unflushed_iter_cb_arg {
432 spa_t *uic_spa;
433 uint64_t uic_txg;
434 void *uic_arg;
435 zdb_log_sm_cb_t uic_cb;
436 } unflushed_iter_cb_arg_t;
438 static int
439 iterate_through_spacemap_logs_cb(space_map_entry_t *sme, void *arg)
441 unflushed_iter_cb_arg_t *uic = arg;
442 return (uic->uic_cb(uic->uic_spa, sme, uic->uic_txg, uic->uic_arg));
445 static void
446 iterate_through_spacemap_logs(spa_t *spa, zdb_log_sm_cb_t cb, void *arg)
448 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
449 return;
451 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
452 for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
453 sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls)) {
454 space_map_t *sm = NULL;
455 VERIFY0(space_map_open(&sm, spa_meta_objset(spa),
456 sls->sls_sm_obj, 0, UINT64_MAX, SPA_MINBLOCKSHIFT));
458 unflushed_iter_cb_arg_t uic = {
459 .uic_spa = spa,
460 .uic_txg = sls->sls_txg,
461 .uic_arg = arg,
462 .uic_cb = cb
464 VERIFY0(space_map_iterate(sm, space_map_length(sm),
465 iterate_through_spacemap_logs_cb, &uic));
466 space_map_close(sm);
468 spa_config_exit(spa, SCL_CONFIG, FTAG);
471 static void
472 verify_livelist_allocs(metaslab_verify_t *mv, uint64_t txg,
473 uint64_t offset, uint64_t size)
475 sublivelist_verify_block_t svb = {{{0}}};
476 DVA_SET_VDEV(&svb.svb_dva, mv->mv_vdid);
477 DVA_SET_OFFSET(&svb.svb_dva, offset);
478 DVA_SET_ASIZE(&svb.svb_dva, size);
479 zfs_btree_index_t where;
480 uint64_t end_offset = offset + size;
483 * Look for an exact match for spacemap entry in the livelist entries.
484 * Then, look for other livelist entries that fall within the range
485 * of the spacemap entry as it may have been condensed
487 sublivelist_verify_block_t *found =
488 zfs_btree_find(&mv->mv_livelist_allocs, &svb, &where);
489 if (found == NULL) {
490 found = zfs_btree_next(&mv->mv_livelist_allocs, &where, &where);
492 for (; found != NULL && DVA_GET_VDEV(&found->svb_dva) == mv->mv_vdid &&
493 DVA_GET_OFFSET(&found->svb_dva) < end_offset;
494 found = zfs_btree_next(&mv->mv_livelist_allocs, &where, &where)) {
495 if (found->svb_allocated_txg <= txg) {
496 (void) printf("ERROR: Livelist ALLOC [%llx:%llx] "
497 "from TXG %llx FREED at TXG %llx\n",
498 (u_longlong_t)DVA_GET_OFFSET(&found->svb_dva),
499 (u_longlong_t)DVA_GET_ASIZE(&found->svb_dva),
500 (u_longlong_t)found->svb_allocated_txg,
501 (u_longlong_t)txg);
506 static int
507 metaslab_spacemap_validation_cb(space_map_entry_t *sme, void *arg)
509 metaslab_verify_t *mv = arg;
510 uint64_t offset = sme->sme_offset;
511 uint64_t size = sme->sme_run;
512 uint64_t txg = sme->sme_txg;
514 if (sme->sme_type == SM_ALLOC) {
515 if (range_tree_contains(mv->mv_allocated,
516 offset, size)) {
517 (void) printf("ERROR: DOUBLE ALLOC: "
518 "%llu [%llx:%llx] "
519 "%llu:%llu LOG_SM\n",
520 (u_longlong_t)txg, (u_longlong_t)offset,
521 (u_longlong_t)size, (u_longlong_t)mv->mv_vdid,
522 (u_longlong_t)mv->mv_msid);
523 } else {
524 range_tree_add(mv->mv_allocated,
525 offset, size);
527 } else {
528 if (!range_tree_contains(mv->mv_allocated,
529 offset, size)) {
530 (void) printf("ERROR: DOUBLE FREE: "
531 "%llu [%llx:%llx] "
532 "%llu:%llu LOG_SM\n",
533 (u_longlong_t)txg, (u_longlong_t)offset,
534 (u_longlong_t)size, (u_longlong_t)mv->mv_vdid,
535 (u_longlong_t)mv->mv_msid);
536 } else {
537 range_tree_remove(mv->mv_allocated,
538 offset, size);
542 if (sme->sme_type != SM_ALLOC) {
544 * If something is freed in the spacemap, verify that
545 * it is not listed as allocated in the livelist.
547 verify_livelist_allocs(mv, txg, offset, size);
549 return (0);
552 static int
553 spacemap_check_sm_log_cb(spa_t *spa, space_map_entry_t *sme,
554 uint64_t txg, void *arg)
556 metaslab_verify_t *mv = arg;
557 uint64_t offset = sme->sme_offset;
558 uint64_t vdev_id = sme->sme_vdev;
560 vdev_t *vd = vdev_lookup_top(spa, vdev_id);
562 /* skip indirect vdevs */
563 if (!vdev_is_concrete(vd))
564 return (0);
566 if (vdev_id != mv->mv_vdid)
567 return (0);
569 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
570 if (ms->ms_id != mv->mv_msid)
571 return (0);
573 if (txg < metaslab_unflushed_txg(ms))
574 return (0);
577 ASSERT3U(txg, ==, sme->sme_txg);
578 return (metaslab_spacemap_validation_cb(sme, mv));
581 static void
582 spacemap_check_sm_log(spa_t *spa, metaslab_verify_t *mv)
584 iterate_through_spacemap_logs(spa, spacemap_check_sm_log_cb, mv);
587 static void
588 spacemap_check_ms_sm(space_map_t *sm, metaslab_verify_t *mv)
590 if (sm == NULL)
591 return;
593 VERIFY0(space_map_iterate(sm, space_map_length(sm),
594 metaslab_spacemap_validation_cb, mv));
597 static void iterate_deleted_livelists(spa_t *spa, ll_iter_t func, void *arg);
600 * Transfer blocks from sv_leftover tree to the mv_livelist_allocs if
601 * they are part of that metaslab (mv_msid).
603 static void
604 mv_populate_livelist_allocs(metaslab_verify_t *mv, sublivelist_verify_t *sv)
606 zfs_btree_index_t where;
607 sublivelist_verify_block_t *svb;
608 ASSERT3U(zfs_btree_numnodes(&mv->mv_livelist_allocs), ==, 0);
609 for (svb = zfs_btree_first(&sv->sv_leftover, &where);
610 svb != NULL;
611 svb = zfs_btree_next(&sv->sv_leftover, &where, &where)) {
612 if (DVA_GET_VDEV(&svb->svb_dva) != mv->mv_vdid)
613 continue;
615 if (DVA_GET_OFFSET(&svb->svb_dva) < mv->mv_start &&
616 (DVA_GET_OFFSET(&svb->svb_dva) +
617 DVA_GET_ASIZE(&svb->svb_dva)) > mv->mv_start) {
618 (void) printf("ERROR: Found block that crosses "
619 "metaslab boundary: <%llu:%llx:%llx>\n",
620 (u_longlong_t)DVA_GET_VDEV(&svb->svb_dva),
621 (u_longlong_t)DVA_GET_OFFSET(&svb->svb_dva),
622 (u_longlong_t)DVA_GET_ASIZE(&svb->svb_dva));
623 continue;
626 if (DVA_GET_OFFSET(&svb->svb_dva) < mv->mv_start)
627 continue;
629 if (DVA_GET_OFFSET(&svb->svb_dva) >= mv->mv_end)
630 continue;
632 if ((DVA_GET_OFFSET(&svb->svb_dva) +
633 DVA_GET_ASIZE(&svb->svb_dva)) > mv->mv_end) {
634 (void) printf("ERROR: Found block that crosses "
635 "metaslab boundary: <%llu:%llx:%llx>\n",
636 (u_longlong_t)DVA_GET_VDEV(&svb->svb_dva),
637 (u_longlong_t)DVA_GET_OFFSET(&svb->svb_dva),
638 (u_longlong_t)DVA_GET_ASIZE(&svb->svb_dva));
639 continue;
642 zfs_btree_add(&mv->mv_livelist_allocs, svb);
645 for (svb = zfs_btree_first(&mv->mv_livelist_allocs, &where);
646 svb != NULL;
647 svb = zfs_btree_next(&mv->mv_livelist_allocs, &where, &where)) {
648 zfs_btree_remove(&sv->sv_leftover, svb);
653 * [Livelist Check]
654 * Iterate through all the sublivelists and:
655 * - report leftover frees (**)
656 * - record leftover ALLOCs together with their TXG [see Cross Check]
658 * (**) Note: Double ALLOCs are valid in datasets that have dedup
659 * enabled. Similarly double FREEs are allowed as well but
660 * only if they pair up with a corresponding ALLOC entry once
661 * we our done with our sublivelist iteration.
663 * [Spacemap Check]
664 * for each metaslab:
665 * - iterate over spacemap and then the metaslab's entries in the
666 * spacemap log, then report any double FREEs and ALLOCs (do not
667 * blow up).
669 * [Cross Check]
670 * After finishing the Livelist Check phase and while being in the
671 * Spacemap Check phase, we find all the recorded leftover ALLOCs
672 * of the livelist check that are part of the metaslab that we are
673 * currently looking at in the Spacemap Check. We report any entries
674 * that are marked as ALLOCs in the livelists but have been actually
675 * freed (and potentially allocated again) after their TXG stamp in
676 * the spacemaps. Also report any ALLOCs from the livelists that
677 * belong to indirect vdevs (e.g. their vdev completed removal).
679 * Note that this will miss Log Spacemap entries that cancelled each other
680 * out before being flushed to the metaslab, so we are not guaranteed
681 * to match all erroneous ALLOCs.
683 static void
684 livelist_metaslab_validate(spa_t *spa)
686 (void) printf("Verifying deleted livelist entries\n");
688 sublivelist_verify_t sv;
689 zfs_btree_create(&sv.sv_leftover, livelist_block_compare, NULL,
690 sizeof (sublivelist_verify_block_t));
691 iterate_deleted_livelists(spa, livelist_verify, &sv);
693 (void) printf("Verifying metaslab entries\n");
694 vdev_t *rvd = spa->spa_root_vdev;
695 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
696 vdev_t *vd = rvd->vdev_child[c];
698 if (!vdev_is_concrete(vd))
699 continue;
701 for (uint64_t mid = 0; mid < vd->vdev_ms_count; mid++) {
702 metaslab_t *m = vd->vdev_ms[mid];
704 (void) fprintf(stderr,
705 "\rverifying concrete vdev %llu, "
706 "metaslab %llu of %llu ...",
707 (longlong_t)vd->vdev_id,
708 (longlong_t)mid,
709 (longlong_t)vd->vdev_ms_count);
711 uint64_t shift, start;
712 range_seg_type_t type =
713 metaslab_calculate_range_tree_type(vd, m,
714 &start, &shift);
715 metaslab_verify_t mv;
716 mv.mv_allocated = range_tree_create(NULL,
717 type, NULL, start, shift);
718 mv.mv_vdid = vd->vdev_id;
719 mv.mv_msid = m->ms_id;
720 mv.mv_start = m->ms_start;
721 mv.mv_end = m->ms_start + m->ms_size;
722 zfs_btree_create(&mv.mv_livelist_allocs,
723 livelist_block_compare, NULL,
724 sizeof (sublivelist_verify_block_t));
726 mv_populate_livelist_allocs(&mv, &sv);
728 spacemap_check_ms_sm(m->ms_sm, &mv);
729 spacemap_check_sm_log(spa, &mv);
731 range_tree_vacate(mv.mv_allocated, NULL, NULL);
732 range_tree_destroy(mv.mv_allocated);
733 zfs_btree_clear(&mv.mv_livelist_allocs);
734 zfs_btree_destroy(&mv.mv_livelist_allocs);
737 (void) fprintf(stderr, "\n");
740 * If there are any segments in the leftover tree after we walked
741 * through all the metaslabs in the concrete vdevs then this means
742 * that we have segments in the livelists that belong to indirect
743 * vdevs and are marked as allocated.
745 if (zfs_btree_numnodes(&sv.sv_leftover) == 0) {
746 zfs_btree_destroy(&sv.sv_leftover);
747 return;
749 (void) printf("ERROR: Found livelist blocks marked as allocated "
750 "for indirect vdevs:\n");
752 zfs_btree_index_t *where = NULL;
753 sublivelist_verify_block_t *svb;
754 while ((svb = zfs_btree_destroy_nodes(&sv.sv_leftover, &where)) !=
755 NULL) {
756 int vdev_id = DVA_GET_VDEV(&svb->svb_dva);
757 ASSERT3U(vdev_id, <, rvd->vdev_children);
758 vdev_t *vd = rvd->vdev_child[vdev_id];
759 ASSERT(!vdev_is_concrete(vd));
760 (void) printf("<%d:%llx:%llx> TXG %llx\n",
761 vdev_id, (u_longlong_t)DVA_GET_OFFSET(&svb->svb_dva),
762 (u_longlong_t)DVA_GET_ASIZE(&svb->svb_dva),
763 (u_longlong_t)svb->svb_allocated_txg);
765 (void) printf("\n");
766 zfs_btree_destroy(&sv.sv_leftover);
770 * These libumem hooks provide a reasonable set of defaults for the allocator's
771 * debugging facilities.
773 const char *
774 _umem_debug_init(void)
776 return ("default,verbose"); /* $UMEM_DEBUG setting */
779 const char *
780 _umem_logging_init(void)
782 return ("fail,contents"); /* $UMEM_LOGGING setting */
785 static void
786 usage(void)
788 (void) fprintf(stderr,
789 "Usage:\t%s [-AbcdDFGhikLMPsvXy] [-e [-V] [-p <path> ...]] "
790 "[-I <inflight I/Os>]\n"
791 "\t\t[-o <var>=<value>]... [-t <txg>] [-U <cache>] [-x <dumpdir>]\n"
792 "\t\t[-K <key>]\n"
793 "\t\t[<poolname>[/<dataset | objset id>] [<object | range> ...]]\n"
794 "\t%s [-AdiPv] [-e [-V] [-p <path> ...]] [-U <cache>] [-K <key>]\n"
795 "\t\t[<poolname>[/<dataset | objset id>] [<object | range> ...]\n"
796 "\t%s -B [-e [-V] [-p <path> ...]] [-I <inflight I/Os>]\n"
797 "\t\t[-o <var>=<value>]... [-t <txg>] [-U <cache>] [-x <dumpdir>]\n"
798 "\t\t[-K <key>] <poolname>/<objset id> [<backupflags>]\n"
799 "\t%s [-v] <bookmark>\n"
800 "\t%s -C [-A] [-U <cache>] [<poolname>]\n"
801 "\t%s -l [-Aqu] <device>\n"
802 "\t%s -m [-AFLPX] [-e [-V] [-p <path> ...]] [-t <txg>] "
803 "[-U <cache>]\n\t\t<poolname> [<vdev> [<metaslab> ...]]\n"
804 "\t%s -O [-K <key>] <dataset> <path>\n"
805 "\t%s -r [-K <key>] <dataset> <path> <destination>\n"
806 "\t%s -R [-A] [-e [-V] [-p <path> ...]] [-U <cache>]\n"
807 "\t\t<poolname> <vdev>:<offset>:<size>[:<flags>]\n"
808 "\t%s -E [-A] word0:word1:...:word15\n"
809 "\t%s -S [-AP] [-e [-V] [-p <path> ...]] [-U <cache>] "
810 "<poolname>\n\n",
811 cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname,
812 cmdname, cmdname, cmdname, cmdname, cmdname);
814 (void) fprintf(stderr, " Dataset name must include at least one "
815 "separator character '/' or '@'\n");
816 (void) fprintf(stderr, " If dataset name is specified, only that "
817 "dataset is dumped\n");
818 (void) fprintf(stderr, " If object numbers or object number "
819 "ranges are specified, only those\n"
820 " objects or ranges are dumped.\n\n");
821 (void) fprintf(stderr,
822 " Object ranges take the form <start>:<end>[:<flags>]\n"
823 " start Starting object number\n"
824 " end Ending object number, or -1 for no upper bound\n"
825 " flags Optional flags to select object types:\n"
826 " A All objects (this is the default)\n"
827 " d ZFS directories\n"
828 " f ZFS files \n"
829 " m SPA space maps\n"
830 " z ZAPs\n"
831 " - Negate effect of next flag\n\n");
832 (void) fprintf(stderr, " Options to control amount of output:\n");
833 (void) fprintf(stderr, " -b --block-stats "
834 "block statistics\n");
835 (void) fprintf(stderr, " -B --backup "
836 "backup stream\n");
837 (void) fprintf(stderr, " -c --checksum "
838 "checksum all metadata (twice for all data) blocks\n");
839 (void) fprintf(stderr, " -C --config "
840 "config (or cachefile if alone)\n");
841 (void) fprintf(stderr, " -d --datasets "
842 "dataset(s)\n");
843 (void) fprintf(stderr, " -D --dedup-stats "
844 "dedup statistics\n");
845 (void) fprintf(stderr, " -E --embedded-block-pointer=INTEGER\n"
846 " decode and display block "
847 "from an embedded block pointer\n");
848 (void) fprintf(stderr, " -h --history "
849 "pool history\n");
850 (void) fprintf(stderr, " -i --intent-logs "
851 "intent logs\n");
852 (void) fprintf(stderr, " -l --label "
853 "read label contents\n");
854 (void) fprintf(stderr, " -k --checkpointed-state "
855 "examine the checkpointed state of the pool\n");
856 (void) fprintf(stderr, " -L --disable-leak-tracking "
857 "disable leak tracking (do not load spacemaps)\n");
858 (void) fprintf(stderr, " -m --metaslabs "
859 "metaslabs\n");
860 (void) fprintf(stderr, " -M --metaslab-groups "
861 "metaslab groups\n");
862 (void) fprintf(stderr, " -O --object-lookups "
863 "perform object lookups by path\n");
864 (void) fprintf(stderr, " -r --copy-object "
865 "copy an object by path to file\n");
866 (void) fprintf(stderr, " -R --read-block "
867 "read and display block from a device\n");
868 (void) fprintf(stderr, " -s --io-stats "
869 "report stats on zdb's I/O\n");
870 (void) fprintf(stderr, " -S --simulate-dedup "
871 "simulate dedup to measure effect\n");
872 (void) fprintf(stderr, " -v --verbose "
873 "verbose (applies to all others)\n");
874 (void) fprintf(stderr, " -y --livelist "
875 "perform livelist and metaslab validation on any livelists being "
876 "deleted\n\n");
877 (void) fprintf(stderr, " Below options are intended for use "
878 "with other options:\n");
879 (void) fprintf(stderr, " -A --ignore-assertions "
880 "ignore assertions (-A), enable panic recovery (-AA) or both "
881 "(-AAA)\n");
882 (void) fprintf(stderr, " -e --exported "
883 "pool is exported/destroyed/has altroot/not in a cachefile\n");
884 (void) fprintf(stderr, " -F --automatic-rewind "
885 "attempt automatic rewind within safe range of transaction "
886 "groups\n");
887 (void) fprintf(stderr, " -G --dump-debug-msg "
888 "dump zfs_dbgmsg buffer before exiting\n");
889 (void) fprintf(stderr, " -I --inflight=INTEGER "
890 "specify the maximum number of checksumming I/Os "
891 "[default is 200]\n");
892 (void) fprintf(stderr, " -K --key=KEY "
893 "decryption key for encrypted dataset\n");
894 (void) fprintf(stderr, " -o --option=\"OPTION=INTEGER\" "
895 "set global variable to an unsigned 32-bit integer\n");
896 (void) fprintf(stderr, " -p --path==PATH "
897 "use one or more with -e to specify path to vdev dir\n");
898 (void) fprintf(stderr, " -P --parseable "
899 "print numbers in parseable form\n");
900 (void) fprintf(stderr, " -q --skip-label "
901 "don't print label contents\n");
902 (void) fprintf(stderr, " -t --txg=INTEGER "
903 "highest txg to use when searching for uberblocks\n");
904 (void) fprintf(stderr, " -T --brt-stats "
905 "BRT statistics\n");
906 (void) fprintf(stderr, " -u --uberblock "
907 "uberblock\n");
908 (void) fprintf(stderr, " -U --cachefile=PATH "
909 "use alternate cachefile\n");
910 (void) fprintf(stderr, " -V --verbatim "
911 "do verbatim import\n");
912 (void) fprintf(stderr, " -x --dump-blocks=PATH "
913 "dump all read blocks into specified directory\n");
914 (void) fprintf(stderr, " -X --extreme-rewind "
915 "attempt extreme rewind (does not work with dataset)\n");
916 (void) fprintf(stderr, " -Y --all-reconstruction "
917 "attempt all reconstruction combinations for split blocks\n");
918 (void) fprintf(stderr, " -Z --zstd-headers "
919 "show ZSTD headers \n");
920 (void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
921 "to make only that option verbose\n");
922 (void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
923 exit(1);
926 static void
927 dump_debug_buffer(void)
929 if (dump_opt['G']) {
930 (void) printf("\n");
931 (void) fflush(stdout);
932 zfs_dbgmsg_print("zdb");
937 * Called for usage errors that are discovered after a call to spa_open(),
938 * dmu_bonus_hold(), or pool_match(). abort() is called for other errors.
941 static void
942 fatal(const char *fmt, ...)
944 va_list ap;
946 va_start(ap, fmt);
947 (void) fprintf(stderr, "%s: ", cmdname);
948 (void) vfprintf(stderr, fmt, ap);
949 va_end(ap);
950 (void) fprintf(stderr, "\n");
952 dump_debug_buffer();
954 exit(1);
957 static void
958 dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
960 (void) size;
961 nvlist_t *nv;
962 size_t nvsize = *(uint64_t *)data;
963 char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
965 VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
967 VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
969 umem_free(packed, nvsize);
971 dump_nvlist(nv, 8);
973 nvlist_free(nv);
976 static void
977 dump_history_offsets(objset_t *os, uint64_t object, void *data, size_t size)
979 (void) os, (void) object, (void) size;
980 spa_history_phys_t *shp = data;
982 if (shp == NULL)
983 return;
985 (void) printf("\t\tpool_create_len = %llu\n",
986 (u_longlong_t)shp->sh_pool_create_len);
987 (void) printf("\t\tphys_max_off = %llu\n",
988 (u_longlong_t)shp->sh_phys_max_off);
989 (void) printf("\t\tbof = %llu\n",
990 (u_longlong_t)shp->sh_bof);
991 (void) printf("\t\teof = %llu\n",
992 (u_longlong_t)shp->sh_eof);
993 (void) printf("\t\trecords_lost = %llu\n",
994 (u_longlong_t)shp->sh_records_lost);
997 static void
998 zdb_nicenum(uint64_t num, char *buf, size_t buflen)
1000 if (dump_opt['P'])
1001 (void) snprintf(buf, buflen, "%llu", (longlong_t)num);
1002 else
1003 nicenum(num, buf, buflen);
1006 static void
1007 zdb_nicebytes(uint64_t bytes, char *buf, size_t buflen)
1009 if (dump_opt['P'])
1010 (void) snprintf(buf, buflen, "%llu", (longlong_t)bytes);
1011 else
1012 zfs_nicebytes(bytes, buf, buflen);
1015 static const char histo_stars[] = "****************************************";
1016 static const uint64_t histo_width = sizeof (histo_stars) - 1;
1018 static void
1019 dump_histogram(const uint64_t *histo, int size, int offset)
1021 int i;
1022 int minidx = size - 1;
1023 int maxidx = 0;
1024 uint64_t max = 0;
1026 for (i = 0; i < size; i++) {
1027 if (histo[i] == 0)
1028 continue;
1029 if (histo[i] > max)
1030 max = histo[i];
1031 if (i > maxidx)
1032 maxidx = i;
1033 if (i < minidx)
1034 minidx = i;
1037 if (max < histo_width)
1038 max = histo_width;
1040 for (i = minidx; i <= maxidx; i++) {
1041 (void) printf("\t\t\t%3u: %6llu %s\n",
1042 i + offset, (u_longlong_t)histo[i],
1043 &histo_stars[(max - histo[i]) * histo_width / max]);
1047 static void
1048 dump_zap_stats(objset_t *os, uint64_t object)
1050 int error;
1051 zap_stats_t zs;
1053 error = zap_get_stats(os, object, &zs);
1054 if (error)
1055 return;
1057 if (zs.zs_ptrtbl_len == 0) {
1058 ASSERT(zs.zs_num_blocks == 1);
1059 (void) printf("\tmicrozap: %llu bytes, %llu entries\n",
1060 (u_longlong_t)zs.zs_blocksize,
1061 (u_longlong_t)zs.zs_num_entries);
1062 return;
1065 (void) printf("\tFat ZAP stats:\n");
1067 (void) printf("\t\tPointer table:\n");
1068 (void) printf("\t\t\t%llu elements\n",
1069 (u_longlong_t)zs.zs_ptrtbl_len);
1070 (void) printf("\t\t\tzt_blk: %llu\n",
1071 (u_longlong_t)zs.zs_ptrtbl_zt_blk);
1072 (void) printf("\t\t\tzt_numblks: %llu\n",
1073 (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
1074 (void) printf("\t\t\tzt_shift: %llu\n",
1075 (u_longlong_t)zs.zs_ptrtbl_zt_shift);
1076 (void) printf("\t\t\tzt_blks_copied: %llu\n",
1077 (u_longlong_t)zs.zs_ptrtbl_blks_copied);
1078 (void) printf("\t\t\tzt_nextblk: %llu\n",
1079 (u_longlong_t)zs.zs_ptrtbl_nextblk);
1081 (void) printf("\t\tZAP entries: %llu\n",
1082 (u_longlong_t)zs.zs_num_entries);
1083 (void) printf("\t\tLeaf blocks: %llu\n",
1084 (u_longlong_t)zs.zs_num_leafs);
1085 (void) printf("\t\tTotal blocks: %llu\n",
1086 (u_longlong_t)zs.zs_num_blocks);
1087 (void) printf("\t\tzap_block_type: 0x%llx\n",
1088 (u_longlong_t)zs.zs_block_type);
1089 (void) printf("\t\tzap_magic: 0x%llx\n",
1090 (u_longlong_t)zs.zs_magic);
1091 (void) printf("\t\tzap_salt: 0x%llx\n",
1092 (u_longlong_t)zs.zs_salt);
1094 (void) printf("\t\tLeafs with 2^n pointers:\n");
1095 dump_histogram(zs.zs_leafs_with_2n_pointers, ZAP_HISTOGRAM_SIZE, 0);
1097 (void) printf("\t\tBlocks with n*5 entries:\n");
1098 dump_histogram(zs.zs_blocks_with_n5_entries, ZAP_HISTOGRAM_SIZE, 0);
1100 (void) printf("\t\tBlocks n/10 full:\n");
1101 dump_histogram(zs.zs_blocks_n_tenths_full, ZAP_HISTOGRAM_SIZE, 0);
1103 (void) printf("\t\tEntries with n chunks:\n");
1104 dump_histogram(zs.zs_entries_using_n_chunks, ZAP_HISTOGRAM_SIZE, 0);
1106 (void) printf("\t\tBuckets with n entries:\n");
1107 dump_histogram(zs.zs_buckets_with_n_entries, ZAP_HISTOGRAM_SIZE, 0);
1110 static void
1111 dump_none(objset_t *os, uint64_t object, void *data, size_t size)
1113 (void) os, (void) object, (void) data, (void) size;
1116 static void
1117 dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
1119 (void) os, (void) object, (void) data, (void) size;
1120 (void) printf("\tUNKNOWN OBJECT TYPE\n");
1123 static void
1124 dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
1126 (void) os, (void) object, (void) data, (void) size;
1129 static void
1130 dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
1132 uint64_t *arr;
1133 uint64_t oursize;
1134 if (dump_opt['d'] < 6)
1135 return;
1137 if (data == NULL) {
1138 dmu_object_info_t doi;
1140 VERIFY0(dmu_object_info(os, object, &doi));
1141 size = doi.doi_max_offset;
1143 * We cap the size at 1 mebibyte here to prevent
1144 * allocation failures and nigh-infinite printing if the
1145 * object is extremely large.
1147 oursize = MIN(size, 1 << 20);
1148 arr = kmem_alloc(oursize, KM_SLEEP);
1150 int err = dmu_read(os, object, 0, oursize, arr, 0);
1151 if (err != 0) {
1152 (void) printf("got error %u from dmu_read\n", err);
1153 kmem_free(arr, oursize);
1154 return;
1156 } else {
1158 * Even though the allocation is already done in this code path,
1159 * we still cap the size to prevent excessive printing.
1161 oursize = MIN(size, 1 << 20);
1162 arr = data;
1165 if (size == 0) {
1166 if (data == NULL)
1167 kmem_free(arr, oursize);
1168 (void) printf("\t\t[]\n");
1169 return;
1172 (void) printf("\t\t[%0llx", (u_longlong_t)arr[0]);
1173 for (size_t i = 1; i * sizeof (uint64_t) < oursize; i++) {
1174 if (i % 4 != 0)
1175 (void) printf(", %0llx", (u_longlong_t)arr[i]);
1176 else
1177 (void) printf(",\n\t\t%0llx", (u_longlong_t)arr[i]);
1179 if (oursize != size)
1180 (void) printf(", ... ");
1181 (void) printf("]\n");
1183 if (data == NULL)
1184 kmem_free(arr, oursize);
1187 static void
1188 dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
1190 (void) data, (void) size;
1191 zap_cursor_t zc;
1192 zap_attribute_t attr;
1193 void *prop;
1194 unsigned i;
1196 dump_zap_stats(os, object);
1197 (void) printf("\n");
1199 for (zap_cursor_init(&zc, os, object);
1200 zap_cursor_retrieve(&zc, &attr) == 0;
1201 zap_cursor_advance(&zc)) {
1202 (void) printf("\t\t%s = ", attr.za_name);
1203 if (attr.za_num_integers == 0) {
1204 (void) printf("\n");
1205 continue;
1207 prop = umem_zalloc(attr.za_num_integers *
1208 attr.za_integer_length, UMEM_NOFAIL);
1209 (void) zap_lookup(os, object, attr.za_name,
1210 attr.za_integer_length, attr.za_num_integers, prop);
1211 if (attr.za_integer_length == 1) {
1212 if (strcmp(attr.za_name,
1213 DSL_CRYPTO_KEY_MASTER_KEY) == 0 ||
1214 strcmp(attr.za_name,
1215 DSL_CRYPTO_KEY_HMAC_KEY) == 0 ||
1216 strcmp(attr.za_name, DSL_CRYPTO_KEY_IV) == 0 ||
1217 strcmp(attr.za_name, DSL_CRYPTO_KEY_MAC) == 0 ||
1218 strcmp(attr.za_name, DMU_POOL_CHECKSUM_SALT) == 0) {
1219 uint8_t *u8 = prop;
1221 for (i = 0; i < attr.za_num_integers; i++) {
1222 (void) printf("%02x", u8[i]);
1224 } else {
1225 (void) printf("%s", (char *)prop);
1227 } else {
1228 for (i = 0; i < attr.za_num_integers; i++) {
1229 switch (attr.za_integer_length) {
1230 case 2:
1231 (void) printf("%u ",
1232 ((uint16_t *)prop)[i]);
1233 break;
1234 case 4:
1235 (void) printf("%u ",
1236 ((uint32_t *)prop)[i]);
1237 break;
1238 case 8:
1239 (void) printf("%lld ",
1240 (u_longlong_t)((int64_t *)prop)[i]);
1241 break;
1245 (void) printf("\n");
1246 umem_free(prop, attr.za_num_integers * attr.za_integer_length);
1248 zap_cursor_fini(&zc);
1251 static void
1252 dump_bpobj(objset_t *os, uint64_t object, void *data, size_t size)
1254 bpobj_phys_t *bpop = data;
1255 uint64_t i;
1256 char bytes[32], comp[32], uncomp[32];
1258 /* make sure the output won't get truncated */
1259 _Static_assert(sizeof (bytes) >= NN_NUMBUF_SZ, "bytes truncated");
1260 _Static_assert(sizeof (comp) >= NN_NUMBUF_SZ, "comp truncated");
1261 _Static_assert(sizeof (uncomp) >= NN_NUMBUF_SZ, "uncomp truncated");
1263 if (bpop == NULL)
1264 return;
1266 zdb_nicenum(bpop->bpo_bytes, bytes, sizeof (bytes));
1267 zdb_nicenum(bpop->bpo_comp, comp, sizeof (comp));
1268 zdb_nicenum(bpop->bpo_uncomp, uncomp, sizeof (uncomp));
1270 (void) printf("\t\tnum_blkptrs = %llu\n",
1271 (u_longlong_t)bpop->bpo_num_blkptrs);
1272 (void) printf("\t\tbytes = %s\n", bytes);
1273 if (size >= BPOBJ_SIZE_V1) {
1274 (void) printf("\t\tcomp = %s\n", comp);
1275 (void) printf("\t\tuncomp = %s\n", uncomp);
1277 if (size >= BPOBJ_SIZE_V2) {
1278 (void) printf("\t\tsubobjs = %llu\n",
1279 (u_longlong_t)bpop->bpo_subobjs);
1280 (void) printf("\t\tnum_subobjs = %llu\n",
1281 (u_longlong_t)bpop->bpo_num_subobjs);
1283 if (size >= sizeof (*bpop)) {
1284 (void) printf("\t\tnum_freed = %llu\n",
1285 (u_longlong_t)bpop->bpo_num_freed);
1288 if (dump_opt['d'] < 5)
1289 return;
1291 for (i = 0; i < bpop->bpo_num_blkptrs; i++) {
1292 char blkbuf[BP_SPRINTF_LEN];
1293 blkptr_t bp;
1295 int err = dmu_read(os, object,
1296 i * sizeof (bp), sizeof (bp), &bp, 0);
1297 if (err != 0) {
1298 (void) printf("got error %u from dmu_read\n", err);
1299 break;
1301 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), &bp,
1302 BP_GET_FREE(&bp));
1303 (void) printf("\t%s\n", blkbuf);
1307 static void
1308 dump_bpobj_subobjs(objset_t *os, uint64_t object, void *data, size_t size)
1310 (void) data, (void) size;
1311 dmu_object_info_t doi;
1312 int64_t i;
1314 VERIFY0(dmu_object_info(os, object, &doi));
1315 uint64_t *subobjs = kmem_alloc(doi.doi_max_offset, KM_SLEEP);
1317 int err = dmu_read(os, object, 0, doi.doi_max_offset, subobjs, 0);
1318 if (err != 0) {
1319 (void) printf("got error %u from dmu_read\n", err);
1320 kmem_free(subobjs, doi.doi_max_offset);
1321 return;
1324 int64_t last_nonzero = -1;
1325 for (i = 0; i < doi.doi_max_offset / 8; i++) {
1326 if (subobjs[i] != 0)
1327 last_nonzero = i;
1330 for (i = 0; i <= last_nonzero; i++) {
1331 (void) printf("\t%llu\n", (u_longlong_t)subobjs[i]);
1333 kmem_free(subobjs, doi.doi_max_offset);
1336 static void
1337 dump_ddt_zap(objset_t *os, uint64_t object, void *data, size_t size)
1339 (void) data, (void) size;
1340 dump_zap_stats(os, object);
1341 /* contents are printed elsewhere, properly decoded */
1344 static void
1345 dump_sa_attrs(objset_t *os, uint64_t object, void *data, size_t size)
1347 (void) data, (void) size;
1348 zap_cursor_t zc;
1349 zap_attribute_t attr;
1351 dump_zap_stats(os, object);
1352 (void) printf("\n");
1354 for (zap_cursor_init(&zc, os, object);
1355 zap_cursor_retrieve(&zc, &attr) == 0;
1356 zap_cursor_advance(&zc)) {
1357 (void) printf("\t\t%s = ", attr.za_name);
1358 if (attr.za_num_integers == 0) {
1359 (void) printf("\n");
1360 continue;
1362 (void) printf(" %llx : [%d:%d:%d]\n",
1363 (u_longlong_t)attr.za_first_integer,
1364 (int)ATTR_LENGTH(attr.za_first_integer),
1365 (int)ATTR_BSWAP(attr.za_first_integer),
1366 (int)ATTR_NUM(attr.za_first_integer));
1368 zap_cursor_fini(&zc);
1371 static void
1372 dump_sa_layouts(objset_t *os, uint64_t object, void *data, size_t size)
1374 (void) data, (void) size;
1375 zap_cursor_t zc;
1376 zap_attribute_t attr;
1377 uint16_t *layout_attrs;
1378 unsigned i;
1380 dump_zap_stats(os, object);
1381 (void) printf("\n");
1383 for (zap_cursor_init(&zc, os, object);
1384 zap_cursor_retrieve(&zc, &attr) == 0;
1385 zap_cursor_advance(&zc)) {
1386 (void) printf("\t\t%s = [", attr.za_name);
1387 if (attr.za_num_integers == 0) {
1388 (void) printf("\n");
1389 continue;
1392 VERIFY(attr.za_integer_length == 2);
1393 layout_attrs = umem_zalloc(attr.za_num_integers *
1394 attr.za_integer_length, UMEM_NOFAIL);
1396 VERIFY(zap_lookup(os, object, attr.za_name,
1397 attr.za_integer_length,
1398 attr.za_num_integers, layout_attrs) == 0);
1400 for (i = 0; i != attr.za_num_integers; i++)
1401 (void) printf(" %d ", (int)layout_attrs[i]);
1402 (void) printf("]\n");
1403 umem_free(layout_attrs,
1404 attr.za_num_integers * attr.za_integer_length);
1406 zap_cursor_fini(&zc);
1409 static void
1410 dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
1412 (void) data, (void) size;
1413 zap_cursor_t zc;
1414 zap_attribute_t attr;
1415 const char *typenames[] = {
1416 /* 0 */ "not specified",
1417 /* 1 */ "FIFO",
1418 /* 2 */ "Character Device",
1419 /* 3 */ "3 (invalid)",
1420 /* 4 */ "Directory",
1421 /* 5 */ "5 (invalid)",
1422 /* 6 */ "Block Device",
1423 /* 7 */ "7 (invalid)",
1424 /* 8 */ "Regular File",
1425 /* 9 */ "9 (invalid)",
1426 /* 10 */ "Symbolic Link",
1427 /* 11 */ "11 (invalid)",
1428 /* 12 */ "Socket",
1429 /* 13 */ "Door",
1430 /* 14 */ "Event Port",
1431 /* 15 */ "15 (invalid)",
1434 dump_zap_stats(os, object);
1435 (void) printf("\n");
1437 for (zap_cursor_init(&zc, os, object);
1438 zap_cursor_retrieve(&zc, &attr) == 0;
1439 zap_cursor_advance(&zc)) {
1440 (void) printf("\t\t%s = %lld (type: %s)\n",
1441 attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
1442 typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
1444 zap_cursor_fini(&zc);
1447 static int
1448 get_dtl_refcount(vdev_t *vd)
1450 int refcount = 0;
1452 if (vd->vdev_ops->vdev_op_leaf) {
1453 space_map_t *sm = vd->vdev_dtl_sm;
1455 if (sm != NULL &&
1456 sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
1457 return (1);
1458 return (0);
1461 for (unsigned c = 0; c < vd->vdev_children; c++)
1462 refcount += get_dtl_refcount(vd->vdev_child[c]);
1463 return (refcount);
1466 static int
1467 get_metaslab_refcount(vdev_t *vd)
1469 int refcount = 0;
1471 if (vd->vdev_top == vd) {
1472 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
1473 space_map_t *sm = vd->vdev_ms[m]->ms_sm;
1475 if (sm != NULL &&
1476 sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
1477 refcount++;
1480 for (unsigned c = 0; c < vd->vdev_children; c++)
1481 refcount += get_metaslab_refcount(vd->vdev_child[c]);
1483 return (refcount);
1486 static int
1487 get_obsolete_refcount(vdev_t *vd)
1489 uint64_t obsolete_sm_object;
1490 int refcount = 0;
1492 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
1493 if (vd->vdev_top == vd && obsolete_sm_object != 0) {
1494 dmu_object_info_t doi;
1495 VERIFY0(dmu_object_info(vd->vdev_spa->spa_meta_objset,
1496 obsolete_sm_object, &doi));
1497 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
1498 refcount++;
1500 } else {
1501 ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
1502 ASSERT3U(obsolete_sm_object, ==, 0);
1504 for (unsigned c = 0; c < vd->vdev_children; c++) {
1505 refcount += get_obsolete_refcount(vd->vdev_child[c]);
1508 return (refcount);
1511 static int
1512 get_prev_obsolete_spacemap_refcount(spa_t *spa)
1514 uint64_t prev_obj =
1515 spa->spa_condensing_indirect_phys.scip_prev_obsolete_sm_object;
1516 if (prev_obj != 0) {
1517 dmu_object_info_t doi;
1518 VERIFY0(dmu_object_info(spa->spa_meta_objset, prev_obj, &doi));
1519 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
1520 return (1);
1523 return (0);
1526 static int
1527 get_checkpoint_refcount(vdev_t *vd)
1529 int refcount = 0;
1531 if (vd->vdev_top == vd && vd->vdev_top_zap != 0 &&
1532 zap_contains(spa_meta_objset(vd->vdev_spa),
1533 vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) == 0)
1534 refcount++;
1536 for (uint64_t c = 0; c < vd->vdev_children; c++)
1537 refcount += get_checkpoint_refcount(vd->vdev_child[c]);
1539 return (refcount);
1542 static int
1543 get_log_spacemap_refcount(spa_t *spa)
1545 return (avl_numnodes(&spa->spa_sm_logs_by_txg));
1548 static int
1549 verify_spacemap_refcounts(spa_t *spa)
1551 uint64_t expected_refcount = 0;
1552 uint64_t actual_refcount;
1554 (void) feature_get_refcount(spa,
1555 &spa_feature_table[SPA_FEATURE_SPACEMAP_HISTOGRAM],
1556 &expected_refcount);
1557 actual_refcount = get_dtl_refcount(spa->spa_root_vdev);
1558 actual_refcount += get_metaslab_refcount(spa->spa_root_vdev);
1559 actual_refcount += get_obsolete_refcount(spa->spa_root_vdev);
1560 actual_refcount += get_prev_obsolete_spacemap_refcount(spa);
1561 actual_refcount += get_checkpoint_refcount(spa->spa_root_vdev);
1562 actual_refcount += get_log_spacemap_refcount(spa);
1564 if (expected_refcount != actual_refcount) {
1565 (void) printf("space map refcount mismatch: expected %lld != "
1566 "actual %lld\n",
1567 (longlong_t)expected_refcount,
1568 (longlong_t)actual_refcount);
1569 return (2);
1571 return (0);
1574 static void
1575 dump_spacemap(objset_t *os, space_map_t *sm)
1577 const char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
1578 "INVALID", "INVALID", "INVALID", "INVALID" };
1580 if (sm == NULL)
1581 return;
1583 (void) printf("space map object %llu:\n",
1584 (longlong_t)sm->sm_object);
1585 (void) printf(" smp_length = 0x%llx\n",
1586 (longlong_t)sm->sm_phys->smp_length);
1587 (void) printf(" smp_alloc = 0x%llx\n",
1588 (longlong_t)sm->sm_phys->smp_alloc);
1590 if (dump_opt['d'] < 6 && dump_opt['m'] < 4)
1591 return;
1594 * Print out the freelist entries in both encoded and decoded form.
1596 uint8_t mapshift = sm->sm_shift;
1597 int64_t alloc = 0;
1598 uint64_t word, entry_id = 0;
1599 for (uint64_t offset = 0; offset < space_map_length(sm);
1600 offset += sizeof (word)) {
1602 VERIFY0(dmu_read(os, space_map_object(sm), offset,
1603 sizeof (word), &word, DMU_READ_PREFETCH));
1605 if (sm_entry_is_debug(word)) {
1606 uint64_t de_txg = SM_DEBUG_TXG_DECODE(word);
1607 uint64_t de_sync_pass = SM_DEBUG_SYNCPASS_DECODE(word);
1608 if (de_txg == 0) {
1609 (void) printf(
1610 "\t [%6llu] PADDING\n",
1611 (u_longlong_t)entry_id);
1612 } else {
1613 (void) printf(
1614 "\t [%6llu] %s: txg %llu pass %llu\n",
1615 (u_longlong_t)entry_id,
1616 ddata[SM_DEBUG_ACTION_DECODE(word)],
1617 (u_longlong_t)de_txg,
1618 (u_longlong_t)de_sync_pass);
1620 entry_id++;
1621 continue;
1624 uint8_t words;
1625 char entry_type;
1626 uint64_t entry_off, entry_run, entry_vdev = SM_NO_VDEVID;
1628 if (sm_entry_is_single_word(word)) {
1629 entry_type = (SM_TYPE_DECODE(word) == SM_ALLOC) ?
1630 'A' : 'F';
1631 entry_off = (SM_OFFSET_DECODE(word) << mapshift) +
1632 sm->sm_start;
1633 entry_run = SM_RUN_DECODE(word) << mapshift;
1634 words = 1;
1635 } else {
1636 /* it is a two-word entry so we read another word */
1637 ASSERT(sm_entry_is_double_word(word));
1639 uint64_t extra_word;
1640 offset += sizeof (extra_word);
1641 VERIFY0(dmu_read(os, space_map_object(sm), offset,
1642 sizeof (extra_word), &extra_word,
1643 DMU_READ_PREFETCH));
1645 ASSERT3U(offset, <=, space_map_length(sm));
1647 entry_run = SM2_RUN_DECODE(word) << mapshift;
1648 entry_vdev = SM2_VDEV_DECODE(word);
1649 entry_type = (SM2_TYPE_DECODE(extra_word) == SM_ALLOC) ?
1650 'A' : 'F';
1651 entry_off = (SM2_OFFSET_DECODE(extra_word) <<
1652 mapshift) + sm->sm_start;
1653 words = 2;
1656 (void) printf("\t [%6llu] %c range:"
1657 " %010llx-%010llx size: %06llx vdev: %06llu words: %u\n",
1658 (u_longlong_t)entry_id,
1659 entry_type, (u_longlong_t)entry_off,
1660 (u_longlong_t)(entry_off + entry_run),
1661 (u_longlong_t)entry_run,
1662 (u_longlong_t)entry_vdev, words);
1664 if (entry_type == 'A')
1665 alloc += entry_run;
1666 else
1667 alloc -= entry_run;
1668 entry_id++;
1670 if (alloc != space_map_allocated(sm)) {
1671 (void) printf("space_map_object alloc (%lld) INCONSISTENT "
1672 "with space map summary (%lld)\n",
1673 (longlong_t)space_map_allocated(sm), (longlong_t)alloc);
1677 static void
1678 dump_metaslab_stats(metaslab_t *msp)
1680 char maxbuf[32];
1681 range_tree_t *rt = msp->ms_allocatable;
1682 zfs_btree_t *t = &msp->ms_allocatable_by_size;
1683 int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
1685 /* max sure nicenum has enough space */
1686 _Static_assert(sizeof (maxbuf) >= NN_NUMBUF_SZ, "maxbuf truncated");
1688 zdb_nicenum(metaslab_largest_allocatable(msp), maxbuf, sizeof (maxbuf));
1690 (void) printf("\t %25s %10lu %7s %6s %4s %4d%%\n",
1691 "segments", zfs_btree_numnodes(t), "maxsize", maxbuf,
1692 "freepct", free_pct);
1693 (void) printf("\tIn-memory histogram:\n");
1694 dump_histogram(rt->rt_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1697 static void
1698 dump_metaslab(metaslab_t *msp)
1700 vdev_t *vd = msp->ms_group->mg_vd;
1701 spa_t *spa = vd->vdev_spa;
1702 space_map_t *sm = msp->ms_sm;
1703 char freebuf[32];
1705 zdb_nicenum(msp->ms_size - space_map_allocated(sm), freebuf,
1706 sizeof (freebuf));
1708 (void) printf(
1709 "\tmetaslab %6llu offset %12llx spacemap %6llu free %5s\n",
1710 (u_longlong_t)msp->ms_id, (u_longlong_t)msp->ms_start,
1711 (u_longlong_t)space_map_object(sm), freebuf);
1713 if (dump_opt['m'] > 2 && !dump_opt['L']) {
1714 mutex_enter(&msp->ms_lock);
1715 VERIFY0(metaslab_load(msp));
1716 range_tree_stat_verify(msp->ms_allocatable);
1717 dump_metaslab_stats(msp);
1718 metaslab_unload(msp);
1719 mutex_exit(&msp->ms_lock);
1722 if (dump_opt['m'] > 1 && sm != NULL &&
1723 spa_feature_is_active(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
1725 * The space map histogram represents free space in chunks
1726 * of sm_shift (i.e. bucket 0 refers to 2^sm_shift).
1728 (void) printf("\tOn-disk histogram:\t\tfragmentation %llu\n",
1729 (u_longlong_t)msp->ms_fragmentation);
1730 dump_histogram(sm->sm_phys->smp_histogram,
1731 SPACE_MAP_HISTOGRAM_SIZE, sm->sm_shift);
1734 if (vd->vdev_ops == &vdev_draid_ops)
1735 ASSERT3U(msp->ms_size, <=, 1ULL << vd->vdev_ms_shift);
1736 else
1737 ASSERT3U(msp->ms_size, ==, 1ULL << vd->vdev_ms_shift);
1739 dump_spacemap(spa->spa_meta_objset, msp->ms_sm);
1741 if (spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP)) {
1742 (void) printf("\tFlush data:\n\tunflushed txg=%llu\n\n",
1743 (u_longlong_t)metaslab_unflushed_txg(msp));
1747 static void
1748 print_vdev_metaslab_header(vdev_t *vd)
1750 vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
1751 const char *bias_str = "";
1752 if (alloc_bias == VDEV_BIAS_LOG || vd->vdev_islog) {
1753 bias_str = VDEV_ALLOC_BIAS_LOG;
1754 } else if (alloc_bias == VDEV_BIAS_SPECIAL) {
1755 bias_str = VDEV_ALLOC_BIAS_SPECIAL;
1756 } else if (alloc_bias == VDEV_BIAS_DEDUP) {
1757 bias_str = VDEV_ALLOC_BIAS_DEDUP;
1760 uint64_t ms_flush_data_obj = 0;
1761 if (vd->vdev_top_zap != 0) {
1762 int error = zap_lookup(spa_meta_objset(vd->vdev_spa),
1763 vd->vdev_top_zap, VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS,
1764 sizeof (uint64_t), 1, &ms_flush_data_obj);
1765 if (error != ENOENT) {
1766 ASSERT0(error);
1770 (void) printf("\tvdev %10llu %s",
1771 (u_longlong_t)vd->vdev_id, bias_str);
1773 if (ms_flush_data_obj != 0) {
1774 (void) printf(" ms_unflushed_phys object %llu",
1775 (u_longlong_t)ms_flush_data_obj);
1778 (void) printf("\n\t%-10s%5llu %-19s %-15s %-12s\n",
1779 "metaslabs", (u_longlong_t)vd->vdev_ms_count,
1780 "offset", "spacemap", "free");
1781 (void) printf("\t%15s %19s %15s %12s\n",
1782 "---------------", "-------------------",
1783 "---------------", "------------");
1786 static void
1787 dump_metaslab_groups(spa_t *spa, boolean_t show_special)
1789 vdev_t *rvd = spa->spa_root_vdev;
1790 metaslab_class_t *mc = spa_normal_class(spa);
1791 metaslab_class_t *smc = spa_special_class(spa);
1792 uint64_t fragmentation;
1794 metaslab_class_histogram_verify(mc);
1796 for (unsigned c = 0; c < rvd->vdev_children; c++) {
1797 vdev_t *tvd = rvd->vdev_child[c];
1798 metaslab_group_t *mg = tvd->vdev_mg;
1800 if (mg == NULL || (mg->mg_class != mc &&
1801 (!show_special || mg->mg_class != smc)))
1802 continue;
1804 metaslab_group_histogram_verify(mg);
1805 mg->mg_fragmentation = metaslab_group_fragmentation(mg);
1807 (void) printf("\tvdev %10llu\t\tmetaslabs%5llu\t\t"
1808 "fragmentation",
1809 (u_longlong_t)tvd->vdev_id,
1810 (u_longlong_t)tvd->vdev_ms_count);
1811 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
1812 (void) printf("%3s\n", "-");
1813 } else {
1814 (void) printf("%3llu%%\n",
1815 (u_longlong_t)mg->mg_fragmentation);
1817 dump_histogram(mg->mg_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1820 (void) printf("\tpool %s\tfragmentation", spa_name(spa));
1821 fragmentation = metaslab_class_fragmentation(mc);
1822 if (fragmentation == ZFS_FRAG_INVALID)
1823 (void) printf("\t%3s\n", "-");
1824 else
1825 (void) printf("\t%3llu%%\n", (u_longlong_t)fragmentation);
1826 dump_histogram(mc->mc_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1829 static void
1830 print_vdev_indirect(vdev_t *vd)
1832 vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
1833 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
1834 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
1836 if (vim == NULL) {
1837 ASSERT3P(vib, ==, NULL);
1838 return;
1841 ASSERT3U(vdev_indirect_mapping_object(vim), ==,
1842 vic->vic_mapping_object);
1843 ASSERT3U(vdev_indirect_births_object(vib), ==,
1844 vic->vic_births_object);
1846 (void) printf("indirect births obj %llu:\n",
1847 (longlong_t)vic->vic_births_object);
1848 (void) printf(" vib_count = %llu\n",
1849 (longlong_t)vdev_indirect_births_count(vib));
1850 for (uint64_t i = 0; i < vdev_indirect_births_count(vib); i++) {
1851 vdev_indirect_birth_entry_phys_t *cur_vibe =
1852 &vib->vib_entries[i];
1853 (void) printf("\toffset %llx -> txg %llu\n",
1854 (longlong_t)cur_vibe->vibe_offset,
1855 (longlong_t)cur_vibe->vibe_phys_birth_txg);
1857 (void) printf("\n");
1859 (void) printf("indirect mapping obj %llu:\n",
1860 (longlong_t)vic->vic_mapping_object);
1861 (void) printf(" vim_max_offset = 0x%llx\n",
1862 (longlong_t)vdev_indirect_mapping_max_offset(vim));
1863 (void) printf(" vim_bytes_mapped = 0x%llx\n",
1864 (longlong_t)vdev_indirect_mapping_bytes_mapped(vim));
1865 (void) printf(" vim_count = %llu\n",
1866 (longlong_t)vdev_indirect_mapping_num_entries(vim));
1868 if (dump_opt['d'] <= 5 && dump_opt['m'] <= 3)
1869 return;
1871 uint32_t *counts = vdev_indirect_mapping_load_obsolete_counts(vim);
1873 for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
1874 vdev_indirect_mapping_entry_phys_t *vimep =
1875 &vim->vim_entries[i];
1876 (void) printf("\t<%llx:%llx:%llx> -> "
1877 "<%llx:%llx:%llx> (%x obsolete)\n",
1878 (longlong_t)vd->vdev_id,
1879 (longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
1880 (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1881 (longlong_t)DVA_GET_VDEV(&vimep->vimep_dst),
1882 (longlong_t)DVA_GET_OFFSET(&vimep->vimep_dst),
1883 (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1884 counts[i]);
1886 (void) printf("\n");
1888 uint64_t obsolete_sm_object;
1889 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
1890 if (obsolete_sm_object != 0) {
1891 objset_t *mos = vd->vdev_spa->spa_meta_objset;
1892 (void) printf("obsolete space map object %llu:\n",
1893 (u_longlong_t)obsolete_sm_object);
1894 ASSERT(vd->vdev_obsolete_sm != NULL);
1895 ASSERT3U(space_map_object(vd->vdev_obsolete_sm), ==,
1896 obsolete_sm_object);
1897 dump_spacemap(mos, vd->vdev_obsolete_sm);
1898 (void) printf("\n");
1902 static void
1903 dump_metaslabs(spa_t *spa)
1905 vdev_t *vd, *rvd = spa->spa_root_vdev;
1906 uint64_t m, c = 0, children = rvd->vdev_children;
1908 (void) printf("\nMetaslabs:\n");
1910 if (!dump_opt['d'] && zopt_metaslab_args > 0) {
1911 c = zopt_metaslab[0];
1913 if (c >= children)
1914 (void) fatal("bad vdev id: %llu", (u_longlong_t)c);
1916 if (zopt_metaslab_args > 1) {
1917 vd = rvd->vdev_child[c];
1918 print_vdev_metaslab_header(vd);
1920 for (m = 1; m < zopt_metaslab_args; m++) {
1921 if (zopt_metaslab[m] < vd->vdev_ms_count)
1922 dump_metaslab(
1923 vd->vdev_ms[zopt_metaslab[m]]);
1924 else
1925 (void) fprintf(stderr, "bad metaslab "
1926 "number %llu\n",
1927 (u_longlong_t)zopt_metaslab[m]);
1929 (void) printf("\n");
1930 return;
1932 children = c + 1;
1934 for (; c < children; c++) {
1935 vd = rvd->vdev_child[c];
1936 print_vdev_metaslab_header(vd);
1938 print_vdev_indirect(vd);
1940 for (m = 0; m < vd->vdev_ms_count; m++)
1941 dump_metaslab(vd->vdev_ms[m]);
1942 (void) printf("\n");
1946 static void
1947 dump_log_spacemaps(spa_t *spa)
1949 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
1950 return;
1952 (void) printf("\nLog Space Maps in Pool:\n");
1953 for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
1954 sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls)) {
1955 space_map_t *sm = NULL;
1956 VERIFY0(space_map_open(&sm, spa_meta_objset(spa),
1957 sls->sls_sm_obj, 0, UINT64_MAX, SPA_MINBLOCKSHIFT));
1959 (void) printf("Log Spacemap object %llu txg %llu\n",
1960 (u_longlong_t)sls->sls_sm_obj, (u_longlong_t)sls->sls_txg);
1961 dump_spacemap(spa->spa_meta_objset, sm);
1962 space_map_close(sm);
1964 (void) printf("\n");
1967 static void
1968 dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
1970 const ddt_phys_t *ddp = dde->dde_phys;
1971 const ddt_key_t *ddk = &dde->dde_key;
1972 const char *types[4] = { "ditto", "single", "double", "triple" };
1973 char blkbuf[BP_SPRINTF_LEN];
1974 blkptr_t blk;
1975 int p;
1977 for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1978 if (ddp->ddp_phys_birth == 0)
1979 continue;
1980 ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
1981 snprintf_blkptr(blkbuf, sizeof (blkbuf), &blk);
1982 (void) printf("index %llx refcnt %llu %s %s\n",
1983 (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
1984 types[p], blkbuf);
1988 static void
1989 dump_dedup_ratio(const ddt_stat_t *dds)
1991 double rL, rP, rD, D, dedup, compress, copies;
1993 if (dds->dds_blocks == 0)
1994 return;
1996 rL = (double)dds->dds_ref_lsize;
1997 rP = (double)dds->dds_ref_psize;
1998 rD = (double)dds->dds_ref_dsize;
1999 D = (double)dds->dds_dsize;
2001 dedup = rD / D;
2002 compress = rL / rP;
2003 copies = rD / rP;
2005 (void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
2006 "dedup * compress / copies = %.2f\n\n",
2007 dedup, compress, copies, dedup * compress / copies);
2010 static void
2011 dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
2013 char name[DDT_NAMELEN];
2014 ddt_entry_t dde;
2015 uint64_t walk = 0;
2016 dmu_object_info_t doi;
2017 uint64_t count, dspace, mspace;
2018 int error;
2020 error = ddt_object_info(ddt, type, class, &doi);
2022 if (error == ENOENT)
2023 return;
2024 ASSERT(error == 0);
2026 error = ddt_object_count(ddt, type, class, &count);
2027 ASSERT(error == 0);
2028 if (count == 0)
2029 return;
2031 dspace = doi.doi_physical_blocks_512 << 9;
2032 mspace = doi.doi_fill_count * doi.doi_data_block_size;
2034 ddt_object_name(ddt, type, class, name);
2036 (void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
2037 name,
2038 (u_longlong_t)count,
2039 (u_longlong_t)(dspace / count),
2040 (u_longlong_t)(mspace / count));
2042 if (dump_opt['D'] < 3)
2043 return;
2045 zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
2047 if (dump_opt['D'] < 4)
2048 return;
2050 if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
2051 return;
2053 (void) printf("%s contents:\n\n", name);
2055 while ((error = ddt_object_walk(ddt, type, class, &walk, &dde)) == 0)
2056 dump_dde(ddt, &dde, walk);
2058 ASSERT3U(error, ==, ENOENT);
2060 (void) printf("\n");
2063 static void
2064 dump_all_ddts(spa_t *spa)
2066 ddt_histogram_t ddh_total = {{{0}}};
2067 ddt_stat_t dds_total = {0};
2069 for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
2070 ddt_t *ddt = spa->spa_ddt[c];
2071 for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
2072 for (enum ddt_class class = 0; class < DDT_CLASSES;
2073 class++) {
2074 dump_ddt(ddt, type, class);
2079 ddt_get_dedup_stats(spa, &dds_total);
2081 if (dds_total.dds_blocks == 0) {
2082 (void) printf("All DDTs are empty\n");
2083 return;
2086 (void) printf("\n");
2088 if (dump_opt['D'] > 1) {
2089 (void) printf("DDT histogram (aggregated over all DDTs):\n");
2090 ddt_get_dedup_histogram(spa, &ddh_total);
2091 zpool_dump_ddt(&dds_total, &ddh_total);
2094 dump_dedup_ratio(&dds_total);
2097 static void
2098 dump_brt(spa_t *spa)
2100 if (!spa_feature_is_enabled(spa, SPA_FEATURE_BLOCK_CLONING)) {
2101 printf("BRT: unsupported on this pool\n");
2102 return;
2105 if (!spa_feature_is_active(spa, SPA_FEATURE_BLOCK_CLONING)) {
2106 printf("BRT: empty\n");
2107 return;
2110 brt_t *brt = spa->spa_brt;
2111 VERIFY(brt);
2113 char count[32], used[32], saved[32];
2114 zdb_nicebytes(brt_get_used(spa), used, sizeof (used));
2115 zdb_nicebytes(brt_get_saved(spa), saved, sizeof (saved));
2116 uint64_t ratio = brt_get_ratio(spa);
2117 printf("BRT: used %s; saved %s; ratio %llu.%02llux\n", used, saved,
2118 (u_longlong_t)(ratio / 100), (u_longlong_t)(ratio % 100));
2120 if (dump_opt['T'] < 2)
2121 return;
2123 for (uint64_t vdevid = 0; vdevid < brt->brt_nvdevs; vdevid++) {
2124 brt_vdev_t *brtvd = &brt->brt_vdevs[vdevid];
2125 if (brtvd == NULL)
2126 continue;
2128 if (!brtvd->bv_initiated) {
2129 printf("BRT: vdev %" PRIu64 ": empty\n", vdevid);
2130 continue;
2133 zdb_nicenum(brtvd->bv_totalcount, count, sizeof (count));
2134 zdb_nicebytes(brtvd->bv_usedspace, used, sizeof (used));
2135 zdb_nicebytes(brtvd->bv_savedspace, saved, sizeof (saved));
2136 printf("BRT: vdev %" PRIu64 ": refcnt %s; used %s; saved %s\n",
2137 vdevid, count, used, saved);
2140 if (dump_opt['T'] < 3)
2141 return;
2143 char dva[64];
2144 printf("\n%-16s %-10s\n", "DVA", "REFCNT");
2146 for (uint64_t vdevid = 0; vdevid < brt->brt_nvdevs; vdevid++) {
2147 brt_vdev_t *brtvd = &brt->brt_vdevs[vdevid];
2148 if (brtvd == NULL || !brtvd->bv_initiated)
2149 continue;
2151 zap_cursor_t zc;
2152 zap_attribute_t za;
2153 for (zap_cursor_init(&zc, brt->brt_mos, brtvd->bv_mos_entries);
2154 zap_cursor_retrieve(&zc, &za) == 0;
2155 zap_cursor_advance(&zc)) {
2156 uint64_t offset = *(uint64_t *)za.za_name;
2157 uint64_t refcnt = za.za_first_integer;
2159 snprintf(dva, sizeof (dva), "%" PRIu64 ":%llx", vdevid,
2160 (u_longlong_t)offset);
2161 printf("%-16s %-10llu\n", dva, (u_longlong_t)refcnt);
2163 zap_cursor_fini(&zc);
2167 static void
2168 dump_dtl_seg(void *arg, uint64_t start, uint64_t size)
2170 char *prefix = arg;
2172 (void) printf("%s [%llu,%llu) length %llu\n",
2173 prefix,
2174 (u_longlong_t)start,
2175 (u_longlong_t)(start + size),
2176 (u_longlong_t)(size));
2179 static void
2180 dump_dtl(vdev_t *vd, int indent)
2182 spa_t *spa = vd->vdev_spa;
2183 boolean_t required;
2184 const char *name[DTL_TYPES] = { "missing", "partial", "scrub",
2185 "outage" };
2186 char prefix[256];
2188 spa_vdev_state_enter(spa, SCL_NONE);
2189 required = vdev_dtl_required(vd);
2190 (void) spa_vdev_state_exit(spa, NULL, 0);
2192 if (indent == 0)
2193 (void) printf("\nDirty time logs:\n\n");
2195 (void) printf("\t%*s%s [%s]\n", indent, "",
2196 vd->vdev_path ? vd->vdev_path :
2197 vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
2198 required ? "DTL-required" : "DTL-expendable");
2200 for (int t = 0; t < DTL_TYPES; t++) {
2201 range_tree_t *rt = vd->vdev_dtl[t];
2202 if (range_tree_space(rt) == 0)
2203 continue;
2204 (void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
2205 indent + 2, "", name[t]);
2206 range_tree_walk(rt, dump_dtl_seg, prefix);
2207 if (dump_opt['d'] > 5 && vd->vdev_children == 0)
2208 dump_spacemap(spa->spa_meta_objset,
2209 vd->vdev_dtl_sm);
2212 for (unsigned c = 0; c < vd->vdev_children; c++)
2213 dump_dtl(vd->vdev_child[c], indent + 4);
2216 static void
2217 dump_history(spa_t *spa)
2219 nvlist_t **events = NULL;
2220 char *buf;
2221 uint64_t resid, len, off = 0;
2222 uint_t num = 0;
2223 int error;
2224 char tbuf[30];
2226 if ((buf = malloc(SPA_OLD_MAXBLOCKSIZE)) == NULL) {
2227 (void) fprintf(stderr, "%s: unable to allocate I/O buffer\n",
2228 __func__);
2229 return;
2232 do {
2233 len = SPA_OLD_MAXBLOCKSIZE;
2235 if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
2236 (void) fprintf(stderr, "Unable to read history: "
2237 "error %d\n", error);
2238 free(buf);
2239 return;
2242 if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
2243 break;
2245 off -= resid;
2246 } while (len != 0);
2248 (void) printf("\nHistory:\n");
2249 for (unsigned i = 0; i < num; i++) {
2250 boolean_t printed = B_FALSE;
2252 if (nvlist_exists(events[i], ZPOOL_HIST_TIME)) {
2253 time_t tsec;
2254 struct tm t;
2256 tsec = fnvlist_lookup_uint64(events[i],
2257 ZPOOL_HIST_TIME);
2258 (void) localtime_r(&tsec, &t);
2259 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
2260 } else {
2261 tbuf[0] = '\0';
2264 if (nvlist_exists(events[i], ZPOOL_HIST_CMD)) {
2265 (void) printf("%s %s\n", tbuf,
2266 fnvlist_lookup_string(events[i], ZPOOL_HIST_CMD));
2267 } else if (nvlist_exists(events[i], ZPOOL_HIST_INT_EVENT)) {
2268 uint64_t ievent;
2270 ievent = fnvlist_lookup_uint64(events[i],
2271 ZPOOL_HIST_INT_EVENT);
2272 if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
2273 goto next;
2275 (void) printf(" %s [internal %s txg:%ju] %s\n",
2276 tbuf,
2277 zfs_history_event_names[ievent],
2278 fnvlist_lookup_uint64(events[i],
2279 ZPOOL_HIST_TXG),
2280 fnvlist_lookup_string(events[i],
2281 ZPOOL_HIST_INT_STR));
2282 } else if (nvlist_exists(events[i], ZPOOL_HIST_INT_NAME)) {
2283 (void) printf("%s [txg:%ju] %s", tbuf,
2284 fnvlist_lookup_uint64(events[i],
2285 ZPOOL_HIST_TXG),
2286 fnvlist_lookup_string(events[i],
2287 ZPOOL_HIST_INT_NAME));
2289 if (nvlist_exists(events[i], ZPOOL_HIST_DSNAME)) {
2290 (void) printf(" %s (%llu)",
2291 fnvlist_lookup_string(events[i],
2292 ZPOOL_HIST_DSNAME),
2293 (u_longlong_t)fnvlist_lookup_uint64(
2294 events[i],
2295 ZPOOL_HIST_DSID));
2298 (void) printf(" %s\n", fnvlist_lookup_string(events[i],
2299 ZPOOL_HIST_INT_STR));
2300 } else if (nvlist_exists(events[i], ZPOOL_HIST_IOCTL)) {
2301 (void) printf("%s ioctl %s\n", tbuf,
2302 fnvlist_lookup_string(events[i],
2303 ZPOOL_HIST_IOCTL));
2305 if (nvlist_exists(events[i], ZPOOL_HIST_INPUT_NVL)) {
2306 (void) printf(" input:\n");
2307 dump_nvlist(fnvlist_lookup_nvlist(events[i],
2308 ZPOOL_HIST_INPUT_NVL), 8);
2310 if (nvlist_exists(events[i], ZPOOL_HIST_OUTPUT_NVL)) {
2311 (void) printf(" output:\n");
2312 dump_nvlist(fnvlist_lookup_nvlist(events[i],
2313 ZPOOL_HIST_OUTPUT_NVL), 8);
2315 if (nvlist_exists(events[i], ZPOOL_HIST_ERRNO)) {
2316 (void) printf(" errno: %lld\n",
2317 (longlong_t)fnvlist_lookup_int64(events[i],
2318 ZPOOL_HIST_ERRNO));
2320 } else {
2321 goto next;
2324 printed = B_TRUE;
2325 next:
2326 if (dump_opt['h'] > 1) {
2327 if (!printed)
2328 (void) printf("unrecognized record:\n");
2329 dump_nvlist(events[i], 2);
2332 free(buf);
2335 static void
2336 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
2338 (void) os, (void) object, (void) data, (void) size;
2341 static uint64_t
2342 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp,
2343 const zbookmark_phys_t *zb)
2345 if (dnp == NULL) {
2346 ASSERT(zb->zb_level < 0);
2347 if (zb->zb_object == 0)
2348 return (zb->zb_blkid);
2349 return (zb->zb_blkid * BP_GET_LSIZE(bp));
2352 ASSERT(zb->zb_level >= 0);
2354 return ((zb->zb_blkid <<
2355 (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
2356 dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
2359 static void
2360 snprintf_zstd_header(spa_t *spa, char *blkbuf, size_t buflen,
2361 const blkptr_t *bp)
2363 abd_t *pabd;
2364 void *buf;
2365 zio_t *zio;
2366 zfs_zstdhdr_t zstd_hdr;
2367 int error;
2369 if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_ZSTD)
2370 return;
2372 if (BP_IS_HOLE(bp))
2373 return;
2375 if (BP_IS_EMBEDDED(bp)) {
2376 buf = malloc(SPA_MAXBLOCKSIZE);
2377 if (buf == NULL) {
2378 (void) fprintf(stderr, "out of memory\n");
2379 exit(1);
2381 decode_embedded_bp_compressed(bp, buf);
2382 memcpy(&zstd_hdr, buf, sizeof (zstd_hdr));
2383 free(buf);
2384 zstd_hdr.c_len = BE_32(zstd_hdr.c_len);
2385 zstd_hdr.raw_version_level = BE_32(zstd_hdr.raw_version_level);
2386 (void) snprintf(blkbuf + strlen(blkbuf),
2387 buflen - strlen(blkbuf),
2388 " ZSTD:size=%u:version=%u:level=%u:EMBEDDED",
2389 zstd_hdr.c_len, zfs_get_hdrversion(&zstd_hdr),
2390 zfs_get_hdrlevel(&zstd_hdr));
2391 return;
2394 pabd = abd_alloc_for_io(SPA_MAXBLOCKSIZE, B_FALSE);
2395 zio = zio_root(spa, NULL, NULL, 0);
2397 /* Decrypt but don't decompress so we can read the compression header */
2398 zio_nowait(zio_read(zio, spa, bp, pabd, BP_GET_PSIZE(bp), NULL, NULL,
2399 ZIO_PRIORITY_SYNC_READ, ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW_COMPRESS,
2400 NULL));
2401 error = zio_wait(zio);
2402 if (error) {
2403 (void) fprintf(stderr, "read failed: %d\n", error);
2404 return;
2406 buf = abd_borrow_buf_copy(pabd, BP_GET_LSIZE(bp));
2407 memcpy(&zstd_hdr, buf, sizeof (zstd_hdr));
2408 zstd_hdr.c_len = BE_32(zstd_hdr.c_len);
2409 zstd_hdr.raw_version_level = BE_32(zstd_hdr.raw_version_level);
2411 (void) snprintf(blkbuf + strlen(blkbuf),
2412 buflen - strlen(blkbuf),
2413 " ZSTD:size=%u:version=%u:level=%u:NORMAL",
2414 zstd_hdr.c_len, zfs_get_hdrversion(&zstd_hdr),
2415 zfs_get_hdrlevel(&zstd_hdr));
2417 abd_return_buf_copy(pabd, buf, BP_GET_LSIZE(bp));
2420 static void
2421 snprintf_blkptr_compact(char *blkbuf, size_t buflen, const blkptr_t *bp,
2422 boolean_t bp_freed)
2424 const dva_t *dva = bp->blk_dva;
2425 int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
2426 int i;
2428 if (dump_opt['b'] >= 6) {
2429 snprintf_blkptr(blkbuf, buflen, bp);
2430 if (bp_freed) {
2431 (void) snprintf(blkbuf + strlen(blkbuf),
2432 buflen - strlen(blkbuf), " %s", "FREE");
2434 return;
2437 if (BP_IS_EMBEDDED(bp)) {
2438 (void) sprintf(blkbuf,
2439 "EMBEDDED et=%u %llxL/%llxP B=%llu",
2440 (int)BPE_GET_ETYPE(bp),
2441 (u_longlong_t)BPE_GET_LSIZE(bp),
2442 (u_longlong_t)BPE_GET_PSIZE(bp),
2443 (u_longlong_t)bp->blk_birth);
2444 return;
2447 blkbuf[0] = '\0';
2449 for (i = 0; i < ndvas; i++)
2450 (void) snprintf(blkbuf + strlen(blkbuf),
2451 buflen - strlen(blkbuf), "%llu:%llx:%llx ",
2452 (u_longlong_t)DVA_GET_VDEV(&dva[i]),
2453 (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
2454 (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
2456 if (BP_IS_HOLE(bp)) {
2457 (void) snprintf(blkbuf + strlen(blkbuf),
2458 buflen - strlen(blkbuf),
2459 "%llxL B=%llu",
2460 (u_longlong_t)BP_GET_LSIZE(bp),
2461 (u_longlong_t)bp->blk_birth);
2462 } else {
2463 (void) snprintf(blkbuf + strlen(blkbuf),
2464 buflen - strlen(blkbuf),
2465 "%llxL/%llxP F=%llu B=%llu/%llu",
2466 (u_longlong_t)BP_GET_LSIZE(bp),
2467 (u_longlong_t)BP_GET_PSIZE(bp),
2468 (u_longlong_t)BP_GET_FILL(bp),
2469 (u_longlong_t)bp->blk_birth,
2470 (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
2471 if (bp_freed)
2472 (void) snprintf(blkbuf + strlen(blkbuf),
2473 buflen - strlen(blkbuf), " %s", "FREE");
2474 (void) snprintf(blkbuf + strlen(blkbuf),
2475 buflen - strlen(blkbuf),
2476 " cksum=%016llx:%016llx:%016llx:%016llx",
2477 (u_longlong_t)bp->blk_cksum.zc_word[0],
2478 (u_longlong_t)bp->blk_cksum.zc_word[1],
2479 (u_longlong_t)bp->blk_cksum.zc_word[2],
2480 (u_longlong_t)bp->blk_cksum.zc_word[3]);
2484 static void
2485 print_indirect(spa_t *spa, blkptr_t *bp, const zbookmark_phys_t *zb,
2486 const dnode_phys_t *dnp)
2488 char blkbuf[BP_SPRINTF_LEN];
2489 int l;
2491 if (!BP_IS_EMBEDDED(bp)) {
2492 ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
2493 ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
2496 (void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
2498 ASSERT(zb->zb_level >= 0);
2500 for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
2501 if (l == zb->zb_level) {
2502 (void) printf("L%llx", (u_longlong_t)zb->zb_level);
2503 } else {
2504 (void) printf(" ");
2508 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp, B_FALSE);
2509 if (dump_opt['Z'] && BP_GET_COMPRESS(bp) == ZIO_COMPRESS_ZSTD)
2510 snprintf_zstd_header(spa, blkbuf, sizeof (blkbuf), bp);
2511 (void) printf("%s\n", blkbuf);
2514 static int
2515 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
2516 blkptr_t *bp, const zbookmark_phys_t *zb)
2518 int err = 0;
2520 if (bp->blk_birth == 0)
2521 return (0);
2523 print_indirect(spa, bp, zb, dnp);
2525 if (BP_GET_LEVEL(bp) > 0 && !BP_IS_HOLE(bp)) {
2526 arc_flags_t flags = ARC_FLAG_WAIT;
2527 int i;
2528 blkptr_t *cbp;
2529 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
2530 arc_buf_t *buf;
2531 uint64_t fill = 0;
2532 ASSERT(!BP_IS_REDACTED(bp));
2534 err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
2535 ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
2536 if (err)
2537 return (err);
2538 ASSERT(buf->b_data);
2540 /* recursively visit blocks below this */
2541 cbp = buf->b_data;
2542 for (i = 0; i < epb; i++, cbp++) {
2543 zbookmark_phys_t czb;
2545 SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
2546 zb->zb_level - 1,
2547 zb->zb_blkid * epb + i);
2548 err = visit_indirect(spa, dnp, cbp, &czb);
2549 if (err)
2550 break;
2551 fill += BP_GET_FILL(cbp);
2553 if (!err)
2554 ASSERT3U(fill, ==, BP_GET_FILL(bp));
2555 arc_buf_destroy(buf, &buf);
2558 return (err);
2561 static void
2562 dump_indirect(dnode_t *dn)
2564 dnode_phys_t *dnp = dn->dn_phys;
2565 zbookmark_phys_t czb;
2567 (void) printf("Indirect blocks:\n");
2569 SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
2570 dn->dn_object, dnp->dn_nlevels - 1, 0);
2571 for (int j = 0; j < dnp->dn_nblkptr; j++) {
2572 czb.zb_blkid = j;
2573 (void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
2574 &dnp->dn_blkptr[j], &czb);
2577 (void) printf("\n");
2580 static void
2581 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
2583 (void) os, (void) object;
2584 dsl_dir_phys_t *dd = data;
2585 time_t crtime;
2586 char nice[32];
2588 /* make sure nicenum has enough space */
2589 _Static_assert(sizeof (nice) >= NN_NUMBUF_SZ, "nice truncated");
2591 if (dd == NULL)
2592 return;
2594 ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
2596 crtime = dd->dd_creation_time;
2597 (void) printf("\t\tcreation_time = %s", ctime(&crtime));
2598 (void) printf("\t\thead_dataset_obj = %llu\n",
2599 (u_longlong_t)dd->dd_head_dataset_obj);
2600 (void) printf("\t\tparent_dir_obj = %llu\n",
2601 (u_longlong_t)dd->dd_parent_obj);
2602 (void) printf("\t\torigin_obj = %llu\n",
2603 (u_longlong_t)dd->dd_origin_obj);
2604 (void) printf("\t\tchild_dir_zapobj = %llu\n",
2605 (u_longlong_t)dd->dd_child_dir_zapobj);
2606 zdb_nicenum(dd->dd_used_bytes, nice, sizeof (nice));
2607 (void) printf("\t\tused_bytes = %s\n", nice);
2608 zdb_nicenum(dd->dd_compressed_bytes, nice, sizeof (nice));
2609 (void) printf("\t\tcompressed_bytes = %s\n", nice);
2610 zdb_nicenum(dd->dd_uncompressed_bytes, nice, sizeof (nice));
2611 (void) printf("\t\tuncompressed_bytes = %s\n", nice);
2612 zdb_nicenum(dd->dd_quota, nice, sizeof (nice));
2613 (void) printf("\t\tquota = %s\n", nice);
2614 zdb_nicenum(dd->dd_reserved, nice, sizeof (nice));
2615 (void) printf("\t\treserved = %s\n", nice);
2616 (void) printf("\t\tprops_zapobj = %llu\n",
2617 (u_longlong_t)dd->dd_props_zapobj);
2618 (void) printf("\t\tdeleg_zapobj = %llu\n",
2619 (u_longlong_t)dd->dd_deleg_zapobj);
2620 (void) printf("\t\tflags = %llx\n",
2621 (u_longlong_t)dd->dd_flags);
2623 #define DO(which) \
2624 zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice, \
2625 sizeof (nice)); \
2626 (void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
2627 DO(HEAD);
2628 DO(SNAP);
2629 DO(CHILD);
2630 DO(CHILD_RSRV);
2631 DO(REFRSRV);
2632 #undef DO
2633 (void) printf("\t\tclones = %llu\n",
2634 (u_longlong_t)dd->dd_clones);
2637 static void
2638 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
2640 (void) os, (void) object;
2641 dsl_dataset_phys_t *ds = data;
2642 time_t crtime;
2643 char used[32], compressed[32], uncompressed[32], unique[32];
2644 char blkbuf[BP_SPRINTF_LEN];
2646 /* make sure nicenum has enough space */
2647 _Static_assert(sizeof (used) >= NN_NUMBUF_SZ, "used truncated");
2648 _Static_assert(sizeof (compressed) >= NN_NUMBUF_SZ,
2649 "compressed truncated");
2650 _Static_assert(sizeof (uncompressed) >= NN_NUMBUF_SZ,
2651 "uncompressed truncated");
2652 _Static_assert(sizeof (unique) >= NN_NUMBUF_SZ, "unique truncated");
2654 if (ds == NULL)
2655 return;
2657 ASSERT(size == sizeof (*ds));
2658 crtime = ds->ds_creation_time;
2659 zdb_nicenum(ds->ds_referenced_bytes, used, sizeof (used));
2660 zdb_nicenum(ds->ds_compressed_bytes, compressed, sizeof (compressed));
2661 zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed,
2662 sizeof (uncompressed));
2663 zdb_nicenum(ds->ds_unique_bytes, unique, sizeof (unique));
2664 snprintf_blkptr(blkbuf, sizeof (blkbuf), &ds->ds_bp);
2666 (void) printf("\t\tdir_obj = %llu\n",
2667 (u_longlong_t)ds->ds_dir_obj);
2668 (void) printf("\t\tprev_snap_obj = %llu\n",
2669 (u_longlong_t)ds->ds_prev_snap_obj);
2670 (void) printf("\t\tprev_snap_txg = %llu\n",
2671 (u_longlong_t)ds->ds_prev_snap_txg);
2672 (void) printf("\t\tnext_snap_obj = %llu\n",
2673 (u_longlong_t)ds->ds_next_snap_obj);
2674 (void) printf("\t\tsnapnames_zapobj = %llu\n",
2675 (u_longlong_t)ds->ds_snapnames_zapobj);
2676 (void) printf("\t\tnum_children = %llu\n",
2677 (u_longlong_t)ds->ds_num_children);
2678 (void) printf("\t\tuserrefs_obj = %llu\n",
2679 (u_longlong_t)ds->ds_userrefs_obj);
2680 (void) printf("\t\tcreation_time = %s", ctime(&crtime));
2681 (void) printf("\t\tcreation_txg = %llu\n",
2682 (u_longlong_t)ds->ds_creation_txg);
2683 (void) printf("\t\tdeadlist_obj = %llu\n",
2684 (u_longlong_t)ds->ds_deadlist_obj);
2685 (void) printf("\t\tused_bytes = %s\n", used);
2686 (void) printf("\t\tcompressed_bytes = %s\n", compressed);
2687 (void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
2688 (void) printf("\t\tunique = %s\n", unique);
2689 (void) printf("\t\tfsid_guid = %llu\n",
2690 (u_longlong_t)ds->ds_fsid_guid);
2691 (void) printf("\t\tguid = %llu\n",
2692 (u_longlong_t)ds->ds_guid);
2693 (void) printf("\t\tflags = %llx\n",
2694 (u_longlong_t)ds->ds_flags);
2695 (void) printf("\t\tnext_clones_obj = %llu\n",
2696 (u_longlong_t)ds->ds_next_clones_obj);
2697 (void) printf("\t\tprops_obj = %llu\n",
2698 (u_longlong_t)ds->ds_props_obj);
2699 (void) printf("\t\tbp = %s\n", blkbuf);
2702 static int
2703 dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2705 (void) arg, (void) tx;
2706 char blkbuf[BP_SPRINTF_LEN];
2708 if (bp->blk_birth != 0) {
2709 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
2710 (void) printf("\t%s\n", blkbuf);
2712 return (0);
2715 static void
2716 dump_bptree(objset_t *os, uint64_t obj, const char *name)
2718 char bytes[32];
2719 bptree_phys_t *bt;
2720 dmu_buf_t *db;
2722 /* make sure nicenum has enough space */
2723 _Static_assert(sizeof (bytes) >= NN_NUMBUF_SZ, "bytes truncated");
2725 if (dump_opt['d'] < 3)
2726 return;
2728 VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
2729 bt = db->db_data;
2730 zdb_nicenum(bt->bt_bytes, bytes, sizeof (bytes));
2731 (void) printf("\n %s: %llu datasets, %s\n",
2732 name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
2733 dmu_buf_rele(db, FTAG);
2735 if (dump_opt['d'] < 5)
2736 return;
2738 (void) printf("\n");
2740 (void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
2743 static int
2744 dump_bpobj_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed, dmu_tx_t *tx)
2746 (void) arg, (void) tx;
2747 char blkbuf[BP_SPRINTF_LEN];
2749 ASSERT(bp->blk_birth != 0);
2750 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp, bp_freed);
2751 (void) printf("\t%s\n", blkbuf);
2752 return (0);
2755 static void
2756 dump_full_bpobj(bpobj_t *bpo, const char *name, int indent)
2758 char bytes[32];
2759 char comp[32];
2760 char uncomp[32];
2761 uint64_t i;
2763 /* make sure nicenum has enough space */
2764 _Static_assert(sizeof (bytes) >= NN_NUMBUF_SZ, "bytes truncated");
2765 _Static_assert(sizeof (comp) >= NN_NUMBUF_SZ, "comp truncated");
2766 _Static_assert(sizeof (uncomp) >= NN_NUMBUF_SZ, "uncomp truncated");
2768 if (dump_opt['d'] < 3)
2769 return;
2771 zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes, sizeof (bytes));
2772 if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
2773 zdb_nicenum(bpo->bpo_phys->bpo_comp, comp, sizeof (comp));
2774 zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp, sizeof (uncomp));
2775 if (bpo->bpo_havefreed) {
2776 (void) printf(" %*s: object %llu, %llu local "
2777 "blkptrs, %llu freed, %llu subobjs in object %llu, "
2778 "%s (%s/%s comp)\n",
2779 indent * 8, name,
2780 (u_longlong_t)bpo->bpo_object,
2781 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2782 (u_longlong_t)bpo->bpo_phys->bpo_num_freed,
2783 (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
2784 (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
2785 bytes, comp, uncomp);
2786 } else {
2787 (void) printf(" %*s: object %llu, %llu local "
2788 "blkptrs, %llu subobjs in object %llu, "
2789 "%s (%s/%s comp)\n",
2790 indent * 8, name,
2791 (u_longlong_t)bpo->bpo_object,
2792 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2793 (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
2794 (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
2795 bytes, comp, uncomp);
2798 for (i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
2799 uint64_t subobj;
2800 bpobj_t subbpo;
2801 int error;
2802 VERIFY0(dmu_read(bpo->bpo_os,
2803 bpo->bpo_phys->bpo_subobjs,
2804 i * sizeof (subobj), sizeof (subobj), &subobj, 0));
2805 error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
2806 if (error != 0) {
2807 (void) printf("ERROR %u while trying to open "
2808 "subobj id %llu\n",
2809 error, (u_longlong_t)subobj);
2810 continue;
2812 dump_full_bpobj(&subbpo, "subobj", indent + 1);
2813 bpobj_close(&subbpo);
2815 } else {
2816 if (bpo->bpo_havefreed) {
2817 (void) printf(" %*s: object %llu, %llu blkptrs, "
2818 "%llu freed, %s\n",
2819 indent * 8, name,
2820 (u_longlong_t)bpo->bpo_object,
2821 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2822 (u_longlong_t)bpo->bpo_phys->bpo_num_freed,
2823 bytes);
2824 } else {
2825 (void) printf(" %*s: object %llu, %llu blkptrs, "
2826 "%s\n",
2827 indent * 8, name,
2828 (u_longlong_t)bpo->bpo_object,
2829 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2830 bytes);
2834 if (dump_opt['d'] < 5)
2835 return;
2838 if (indent == 0) {
2839 (void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
2840 (void) printf("\n");
2844 static int
2845 dump_bookmark(dsl_pool_t *dp, char *name, boolean_t print_redact,
2846 boolean_t print_list)
2848 int err = 0;
2849 zfs_bookmark_phys_t prop;
2850 objset_t *mos = dp->dp_spa->spa_meta_objset;
2851 err = dsl_bookmark_lookup(dp, name, NULL, &prop);
2853 if (err != 0) {
2854 return (err);
2857 (void) printf("\t#%s: ", strchr(name, '#') + 1);
2858 (void) printf("{guid: %llx creation_txg: %llu creation_time: "
2859 "%llu redaction_obj: %llu}\n", (u_longlong_t)prop.zbm_guid,
2860 (u_longlong_t)prop.zbm_creation_txg,
2861 (u_longlong_t)prop.zbm_creation_time,
2862 (u_longlong_t)prop.zbm_redaction_obj);
2864 IMPLY(print_list, print_redact);
2865 if (!print_redact || prop.zbm_redaction_obj == 0)
2866 return (0);
2868 redaction_list_t *rl;
2869 VERIFY0(dsl_redaction_list_hold_obj(dp,
2870 prop.zbm_redaction_obj, FTAG, &rl));
2872 redaction_list_phys_t *rlp = rl->rl_phys;
2873 (void) printf("\tRedacted:\n\t\tProgress: ");
2874 if (rlp->rlp_last_object != UINT64_MAX ||
2875 rlp->rlp_last_blkid != UINT64_MAX) {
2876 (void) printf("%llu %llu (incomplete)\n",
2877 (u_longlong_t)rlp->rlp_last_object,
2878 (u_longlong_t)rlp->rlp_last_blkid);
2879 } else {
2880 (void) printf("complete\n");
2882 (void) printf("\t\tSnapshots: [");
2883 for (unsigned int i = 0; i < rlp->rlp_num_snaps; i++) {
2884 if (i > 0)
2885 (void) printf(", ");
2886 (void) printf("%0llu",
2887 (u_longlong_t)rlp->rlp_snaps[i]);
2889 (void) printf("]\n\t\tLength: %llu\n",
2890 (u_longlong_t)rlp->rlp_num_entries);
2892 if (!print_list) {
2893 dsl_redaction_list_rele(rl, FTAG);
2894 return (0);
2897 if (rlp->rlp_num_entries == 0) {
2898 dsl_redaction_list_rele(rl, FTAG);
2899 (void) printf("\t\tRedaction List: []\n\n");
2900 return (0);
2903 redact_block_phys_t *rbp_buf;
2904 uint64_t size;
2905 dmu_object_info_t doi;
2907 VERIFY0(dmu_object_info(mos, prop.zbm_redaction_obj, &doi));
2908 size = doi.doi_max_offset;
2909 rbp_buf = kmem_alloc(size, KM_SLEEP);
2911 err = dmu_read(mos, prop.zbm_redaction_obj, 0, size,
2912 rbp_buf, 0);
2913 if (err != 0) {
2914 dsl_redaction_list_rele(rl, FTAG);
2915 kmem_free(rbp_buf, size);
2916 return (err);
2919 (void) printf("\t\tRedaction List: [{object: %llx, offset: "
2920 "%llx, blksz: %x, count: %llx}",
2921 (u_longlong_t)rbp_buf[0].rbp_object,
2922 (u_longlong_t)rbp_buf[0].rbp_blkid,
2923 (uint_t)(redact_block_get_size(&rbp_buf[0])),
2924 (u_longlong_t)redact_block_get_count(&rbp_buf[0]));
2926 for (size_t i = 1; i < rlp->rlp_num_entries; i++) {
2927 (void) printf(",\n\t\t{object: %llx, offset: %llx, "
2928 "blksz: %x, count: %llx}",
2929 (u_longlong_t)rbp_buf[i].rbp_object,
2930 (u_longlong_t)rbp_buf[i].rbp_blkid,
2931 (uint_t)(redact_block_get_size(&rbp_buf[i])),
2932 (u_longlong_t)redact_block_get_count(&rbp_buf[i]));
2934 dsl_redaction_list_rele(rl, FTAG);
2935 kmem_free(rbp_buf, size);
2936 (void) printf("]\n\n");
2937 return (0);
2940 static void
2941 dump_bookmarks(objset_t *os, int verbosity)
2943 zap_cursor_t zc;
2944 zap_attribute_t attr;
2945 dsl_dataset_t *ds = dmu_objset_ds(os);
2946 dsl_pool_t *dp = spa_get_dsl(os->os_spa);
2947 objset_t *mos = os->os_spa->spa_meta_objset;
2948 if (verbosity < 4)
2949 return;
2950 dsl_pool_config_enter(dp, FTAG);
2952 for (zap_cursor_init(&zc, mos, ds->ds_bookmarks_obj);
2953 zap_cursor_retrieve(&zc, &attr) == 0;
2954 zap_cursor_advance(&zc)) {
2955 char osname[ZFS_MAX_DATASET_NAME_LEN];
2956 char buf[ZFS_MAX_DATASET_NAME_LEN];
2957 int len;
2958 dmu_objset_name(os, osname);
2959 len = snprintf(buf, sizeof (buf), "%s#%s", osname,
2960 attr.za_name);
2961 VERIFY3S(len, <, ZFS_MAX_DATASET_NAME_LEN);
2962 (void) dump_bookmark(dp, buf, verbosity >= 5, verbosity >= 6);
2964 zap_cursor_fini(&zc);
2965 dsl_pool_config_exit(dp, FTAG);
2968 static void
2969 bpobj_count_refd(bpobj_t *bpo)
2971 mos_obj_refd(bpo->bpo_object);
2973 if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
2974 mos_obj_refd(bpo->bpo_phys->bpo_subobjs);
2975 for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
2976 uint64_t subobj;
2977 bpobj_t subbpo;
2978 int error;
2979 VERIFY0(dmu_read(bpo->bpo_os,
2980 bpo->bpo_phys->bpo_subobjs,
2981 i * sizeof (subobj), sizeof (subobj), &subobj, 0));
2982 error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
2983 if (error != 0) {
2984 (void) printf("ERROR %u while trying to open "
2985 "subobj id %llu\n",
2986 error, (u_longlong_t)subobj);
2987 continue;
2989 bpobj_count_refd(&subbpo);
2990 bpobj_close(&subbpo);
2995 static int
2996 dsl_deadlist_entry_count_refd(void *arg, dsl_deadlist_entry_t *dle)
2998 spa_t *spa = arg;
2999 uint64_t empty_bpobj = spa->spa_dsl_pool->dp_empty_bpobj;
3000 if (dle->dle_bpobj.bpo_object != empty_bpobj)
3001 bpobj_count_refd(&dle->dle_bpobj);
3002 return (0);
3005 static int
3006 dsl_deadlist_entry_dump(void *arg, dsl_deadlist_entry_t *dle)
3008 ASSERT(arg == NULL);
3009 if (dump_opt['d'] >= 5) {
3010 char buf[128];
3011 (void) snprintf(buf, sizeof (buf),
3012 "mintxg %llu -> obj %llu",
3013 (longlong_t)dle->dle_mintxg,
3014 (longlong_t)dle->dle_bpobj.bpo_object);
3016 dump_full_bpobj(&dle->dle_bpobj, buf, 0);
3017 } else {
3018 (void) printf("mintxg %llu -> obj %llu\n",
3019 (longlong_t)dle->dle_mintxg,
3020 (longlong_t)dle->dle_bpobj.bpo_object);
3022 return (0);
3025 static void
3026 dump_blkptr_list(dsl_deadlist_t *dl, const char *name)
3028 char bytes[32];
3029 char comp[32];
3030 char uncomp[32];
3031 char entries[32];
3032 spa_t *spa = dmu_objset_spa(dl->dl_os);
3033 uint64_t empty_bpobj = spa->spa_dsl_pool->dp_empty_bpobj;
3035 if (dl->dl_oldfmt) {
3036 if (dl->dl_bpobj.bpo_object != empty_bpobj)
3037 bpobj_count_refd(&dl->dl_bpobj);
3038 } else {
3039 mos_obj_refd(dl->dl_object);
3040 dsl_deadlist_iterate(dl, dsl_deadlist_entry_count_refd, spa);
3043 /* make sure nicenum has enough space */
3044 _Static_assert(sizeof (bytes) >= NN_NUMBUF_SZ, "bytes truncated");
3045 _Static_assert(sizeof (comp) >= NN_NUMBUF_SZ, "comp truncated");
3046 _Static_assert(sizeof (uncomp) >= NN_NUMBUF_SZ, "uncomp truncated");
3047 _Static_assert(sizeof (entries) >= NN_NUMBUF_SZ, "entries truncated");
3049 if (dump_opt['d'] < 3)
3050 return;
3052 if (dl->dl_oldfmt) {
3053 dump_full_bpobj(&dl->dl_bpobj, "old-format deadlist", 0);
3054 return;
3057 zdb_nicenum(dl->dl_phys->dl_used, bytes, sizeof (bytes));
3058 zdb_nicenum(dl->dl_phys->dl_comp, comp, sizeof (comp));
3059 zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp, sizeof (uncomp));
3060 zdb_nicenum(avl_numnodes(&dl->dl_tree), entries, sizeof (entries));
3061 (void) printf("\n %s: %s (%s/%s comp), %s entries\n",
3062 name, bytes, comp, uncomp, entries);
3064 if (dump_opt['d'] < 4)
3065 return;
3067 (void) putchar('\n');
3069 dsl_deadlist_iterate(dl, dsl_deadlist_entry_dump, NULL);
3072 static int
3073 verify_dd_livelist(objset_t *os)
3075 uint64_t ll_used, used, ll_comp, comp, ll_uncomp, uncomp;
3076 dsl_pool_t *dp = spa_get_dsl(os->os_spa);
3077 dsl_dir_t *dd = os->os_dsl_dataset->ds_dir;
3079 ASSERT(!dmu_objset_is_snapshot(os));
3080 if (!dsl_deadlist_is_open(&dd->dd_livelist))
3081 return (0);
3083 /* Iterate through the livelist to check for duplicates */
3084 dsl_deadlist_iterate(&dd->dd_livelist, sublivelist_verify_lightweight,
3085 NULL);
3087 dsl_pool_config_enter(dp, FTAG);
3088 dsl_deadlist_space(&dd->dd_livelist, &ll_used,
3089 &ll_comp, &ll_uncomp);
3091 dsl_dataset_t *origin_ds;
3092 ASSERT(dsl_pool_config_held(dp));
3093 VERIFY0(dsl_dataset_hold_obj(dp,
3094 dsl_dir_phys(dd)->dd_origin_obj, FTAG, &origin_ds));
3095 VERIFY0(dsl_dataset_space_written(origin_ds, os->os_dsl_dataset,
3096 &used, &comp, &uncomp));
3097 dsl_dataset_rele(origin_ds, FTAG);
3098 dsl_pool_config_exit(dp, FTAG);
3100 * It's possible that the dataset's uncomp space is larger than the
3101 * livelist's because livelists do not track embedded block pointers
3103 if (used != ll_used || comp != ll_comp || uncomp < ll_uncomp) {
3104 char nice_used[32], nice_comp[32], nice_uncomp[32];
3105 (void) printf("Discrepancy in space accounting:\n");
3106 zdb_nicenum(used, nice_used, sizeof (nice_used));
3107 zdb_nicenum(comp, nice_comp, sizeof (nice_comp));
3108 zdb_nicenum(uncomp, nice_uncomp, sizeof (nice_uncomp));
3109 (void) printf("dir: used %s, comp %s, uncomp %s\n",
3110 nice_used, nice_comp, nice_uncomp);
3111 zdb_nicenum(ll_used, nice_used, sizeof (nice_used));
3112 zdb_nicenum(ll_comp, nice_comp, sizeof (nice_comp));
3113 zdb_nicenum(ll_uncomp, nice_uncomp, sizeof (nice_uncomp));
3114 (void) printf("livelist: used %s, comp %s, uncomp %s\n",
3115 nice_used, nice_comp, nice_uncomp);
3116 return (1);
3118 return (0);
3121 static char *key_material = NULL;
3123 static boolean_t
3124 zdb_derive_key(dsl_dir_t *dd, uint8_t *key_out)
3126 uint64_t keyformat, salt, iters;
3127 int i;
3128 unsigned char c;
3130 VERIFY0(zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
3131 zfs_prop_to_name(ZFS_PROP_KEYFORMAT), sizeof (uint64_t),
3132 1, &keyformat));
3134 switch (keyformat) {
3135 case ZFS_KEYFORMAT_HEX:
3136 for (i = 0; i < WRAPPING_KEY_LEN * 2; i += 2) {
3137 if (!isxdigit(key_material[i]) ||
3138 !isxdigit(key_material[i+1]))
3139 return (B_FALSE);
3140 if (sscanf(&key_material[i], "%02hhx", &c) != 1)
3141 return (B_FALSE);
3142 key_out[i / 2] = c;
3144 break;
3146 case ZFS_KEYFORMAT_PASSPHRASE:
3147 VERIFY0(zap_lookup(dd->dd_pool->dp_meta_objset,
3148 dd->dd_crypto_obj, zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT),
3149 sizeof (uint64_t), 1, &salt));
3150 VERIFY0(zap_lookup(dd->dd_pool->dp_meta_objset,
3151 dd->dd_crypto_obj, zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS),
3152 sizeof (uint64_t), 1, &iters));
3154 if (PKCS5_PBKDF2_HMAC_SHA1(key_material, strlen(key_material),
3155 ((uint8_t *)&salt), sizeof (uint64_t), iters,
3156 WRAPPING_KEY_LEN, key_out) != 1)
3157 return (B_FALSE);
3159 break;
3161 default:
3162 fatal("no support for key format %u\n",
3163 (unsigned int) keyformat);
3166 return (B_TRUE);
3169 static char encroot[ZFS_MAX_DATASET_NAME_LEN];
3170 static boolean_t key_loaded = B_FALSE;
3172 static void
3173 zdb_load_key(objset_t *os)
3175 dsl_pool_t *dp;
3176 dsl_dir_t *dd, *rdd;
3177 uint8_t key[WRAPPING_KEY_LEN];
3178 uint64_t rddobj;
3179 int err;
3181 dp = spa_get_dsl(os->os_spa);
3182 dd = os->os_dsl_dataset->ds_dir;
3184 dsl_pool_config_enter(dp, FTAG);
3185 VERIFY0(zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
3186 DSL_CRYPTO_KEY_ROOT_DDOBJ, sizeof (uint64_t), 1, &rddobj));
3187 VERIFY0(dsl_dir_hold_obj(dd->dd_pool, rddobj, NULL, FTAG, &rdd));
3188 dsl_dir_name(rdd, encroot);
3189 dsl_dir_rele(rdd, FTAG);
3191 if (!zdb_derive_key(dd, key))
3192 fatal("couldn't derive encryption key");
3194 dsl_pool_config_exit(dp, FTAG);
3196 ASSERT3U(dsl_dataset_get_keystatus(dd), ==, ZFS_KEYSTATUS_UNAVAILABLE);
3198 dsl_crypto_params_t *dcp;
3199 nvlist_t *crypto_args;
3201 crypto_args = fnvlist_alloc();
3202 fnvlist_add_uint8_array(crypto_args, "wkeydata",
3203 (uint8_t *)key, WRAPPING_KEY_LEN);
3204 VERIFY0(dsl_crypto_params_create_nvlist(DCP_CMD_NONE,
3205 NULL, crypto_args, &dcp));
3206 err = spa_keystore_load_wkey(encroot, dcp, B_FALSE);
3208 dsl_crypto_params_free(dcp, (err != 0));
3209 fnvlist_free(crypto_args);
3211 if (err != 0)
3212 fatal(
3213 "couldn't load encryption key for %s: %s",
3214 encroot, err == ZFS_ERR_CRYPTO_NOTSUP ?
3215 "crypto params not supported" : strerror(err));
3217 ASSERT3U(dsl_dataset_get_keystatus(dd), ==, ZFS_KEYSTATUS_AVAILABLE);
3219 printf("Unlocked encryption root: %s\n", encroot);
3220 key_loaded = B_TRUE;
3223 static void
3224 zdb_unload_key(void)
3226 if (!key_loaded)
3227 return;
3229 VERIFY0(spa_keystore_unload_wkey(encroot));
3230 key_loaded = B_FALSE;
3233 static avl_tree_t idx_tree;
3234 static avl_tree_t domain_tree;
3235 static boolean_t fuid_table_loaded;
3236 static objset_t *sa_os = NULL;
3237 static sa_attr_type_t *sa_attr_table = NULL;
3239 static int
3240 open_objset(const char *path, const void *tag, objset_t **osp)
3242 int err;
3243 uint64_t sa_attrs = 0;
3244 uint64_t version = 0;
3246 VERIFY3P(sa_os, ==, NULL);
3249 * We can't own an objset if it's redacted. Therefore, we do this
3250 * dance: hold the objset, then acquire a long hold on its dataset, then
3251 * release the pool (which is held as part of holding the objset).
3254 if (dump_opt['K']) {
3255 /* decryption requested, try to load keys */
3256 err = dmu_objset_hold(path, tag, osp);
3257 if (err != 0) {
3258 (void) fprintf(stderr, "failed to hold dataset "
3259 "'%s': %s\n",
3260 path, strerror(err));
3261 return (err);
3263 dsl_dataset_long_hold(dmu_objset_ds(*osp), tag);
3264 dsl_pool_rele(dmu_objset_pool(*osp), tag);
3266 /* succeeds or dies */
3267 zdb_load_key(*osp);
3269 /* release it all */
3270 dsl_dataset_long_rele(dmu_objset_ds(*osp), tag);
3271 dsl_dataset_rele(dmu_objset_ds(*osp), tag);
3274 int ds_hold_flags = key_loaded ? DS_HOLD_FLAG_DECRYPT : 0;
3276 err = dmu_objset_hold_flags(path, ds_hold_flags, tag, osp);
3277 if (err != 0) {
3278 (void) fprintf(stderr, "failed to hold dataset '%s': %s\n",
3279 path, strerror(err));
3280 return (err);
3282 dsl_dataset_long_hold(dmu_objset_ds(*osp), tag);
3283 dsl_pool_rele(dmu_objset_pool(*osp), tag);
3285 if (dmu_objset_type(*osp) == DMU_OST_ZFS &&
3286 (key_loaded || !(*osp)->os_encrypted)) {
3287 (void) zap_lookup(*osp, MASTER_NODE_OBJ, ZPL_VERSION_STR,
3288 8, 1, &version);
3289 if (version >= ZPL_VERSION_SA) {
3290 (void) zap_lookup(*osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
3291 8, 1, &sa_attrs);
3293 err = sa_setup(*osp, sa_attrs, zfs_attr_table, ZPL_END,
3294 &sa_attr_table);
3295 if (err != 0) {
3296 (void) fprintf(stderr, "sa_setup failed: %s\n",
3297 strerror(err));
3298 dsl_dataset_long_rele(dmu_objset_ds(*osp), tag);
3299 dsl_dataset_rele_flags(dmu_objset_ds(*osp),
3300 ds_hold_flags, tag);
3301 *osp = NULL;
3304 sa_os = *osp;
3306 return (err);
3309 static void
3310 close_objset(objset_t *os, const void *tag)
3312 VERIFY3P(os, ==, sa_os);
3313 if (os->os_sa != NULL)
3314 sa_tear_down(os);
3315 dsl_dataset_long_rele(dmu_objset_ds(os), tag);
3316 dsl_dataset_rele_flags(dmu_objset_ds(os),
3317 key_loaded ? DS_HOLD_FLAG_DECRYPT : 0, tag);
3318 sa_attr_table = NULL;
3319 sa_os = NULL;
3321 zdb_unload_key();
3324 static void
3325 fuid_table_destroy(void)
3327 if (fuid_table_loaded) {
3328 zfs_fuid_table_destroy(&idx_tree, &domain_tree);
3329 fuid_table_loaded = B_FALSE;
3334 * print uid or gid information.
3335 * For normal POSIX id just the id is printed in decimal format.
3336 * For CIFS files with FUID the fuid is printed in hex followed by
3337 * the domain-rid string.
3339 static void
3340 print_idstr(uint64_t id, const char *id_type)
3342 if (FUID_INDEX(id)) {
3343 const char *domain =
3344 zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
3345 (void) printf("\t%s %llx [%s-%d]\n", id_type,
3346 (u_longlong_t)id, domain, (int)FUID_RID(id));
3347 } else {
3348 (void) printf("\t%s %llu\n", id_type, (u_longlong_t)id);
3353 static void
3354 dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
3356 uint32_t uid_idx, gid_idx;
3358 uid_idx = FUID_INDEX(uid);
3359 gid_idx = FUID_INDEX(gid);
3361 /* Load domain table, if not already loaded */
3362 if (!fuid_table_loaded && (uid_idx || gid_idx)) {
3363 uint64_t fuid_obj;
3365 /* first find the fuid object. It lives in the master node */
3366 VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
3367 8, 1, &fuid_obj) == 0);
3368 zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
3369 (void) zfs_fuid_table_load(os, fuid_obj,
3370 &idx_tree, &domain_tree);
3371 fuid_table_loaded = B_TRUE;
3374 print_idstr(uid, "uid");
3375 print_idstr(gid, "gid");
3378 static void
3379 dump_znode_sa_xattr(sa_handle_t *hdl)
3381 nvlist_t *sa_xattr;
3382 nvpair_t *elem = NULL;
3383 int sa_xattr_size = 0;
3384 int sa_xattr_entries = 0;
3385 int error;
3386 char *sa_xattr_packed;
3388 error = sa_size(hdl, sa_attr_table[ZPL_DXATTR], &sa_xattr_size);
3389 if (error || sa_xattr_size == 0)
3390 return;
3392 sa_xattr_packed = malloc(sa_xattr_size);
3393 if (sa_xattr_packed == NULL)
3394 return;
3396 error = sa_lookup(hdl, sa_attr_table[ZPL_DXATTR],
3397 sa_xattr_packed, sa_xattr_size);
3398 if (error) {
3399 free(sa_xattr_packed);
3400 return;
3403 error = nvlist_unpack(sa_xattr_packed, sa_xattr_size, &sa_xattr, 0);
3404 if (error) {
3405 free(sa_xattr_packed);
3406 return;
3409 while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL)
3410 sa_xattr_entries++;
3412 (void) printf("\tSA xattrs: %d bytes, %d entries\n\n",
3413 sa_xattr_size, sa_xattr_entries);
3414 while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL) {
3415 boolean_t can_print = !dump_opt['P'];
3416 uchar_t *value;
3417 uint_t cnt, idx;
3419 (void) printf("\t\t%s = ", nvpair_name(elem));
3420 nvpair_value_byte_array(elem, &value, &cnt);
3422 for (idx = 0; idx < cnt; ++idx) {
3423 if (!isprint(value[idx])) {
3424 can_print = B_FALSE;
3425 break;
3429 for (idx = 0; idx < cnt; ++idx) {
3430 if (can_print)
3431 (void) putchar(value[idx]);
3432 else
3433 (void) printf("\\%3.3o", value[idx]);
3435 (void) putchar('\n');
3438 nvlist_free(sa_xattr);
3439 free(sa_xattr_packed);
3442 static void
3443 dump_znode_symlink(sa_handle_t *hdl)
3445 int sa_symlink_size = 0;
3446 char linktarget[MAXPATHLEN];
3447 int error;
3449 error = sa_size(hdl, sa_attr_table[ZPL_SYMLINK], &sa_symlink_size);
3450 if (error || sa_symlink_size == 0) {
3451 return;
3453 if (sa_symlink_size >= sizeof (linktarget)) {
3454 (void) printf("symlink size %d is too large\n",
3455 sa_symlink_size);
3456 return;
3458 linktarget[sa_symlink_size] = '\0';
3459 if (sa_lookup(hdl, sa_attr_table[ZPL_SYMLINK],
3460 &linktarget, sa_symlink_size) == 0)
3461 (void) printf("\ttarget %s\n", linktarget);
3464 static void
3465 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
3467 (void) data, (void) size;
3468 char path[MAXPATHLEN * 2]; /* allow for xattr and failure prefix */
3469 sa_handle_t *hdl;
3470 uint64_t xattr, rdev, gen;
3471 uint64_t uid, gid, mode, fsize, parent, links;
3472 uint64_t pflags;
3473 uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
3474 time_t z_crtime, z_atime, z_mtime, z_ctime;
3475 sa_bulk_attr_t bulk[12];
3476 int idx = 0;
3477 int error;
3479 VERIFY3P(os, ==, sa_os);
3480 if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
3481 (void) printf("Failed to get handle for SA znode\n");
3482 return;
3485 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
3486 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
3487 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
3488 &links, 8);
3489 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
3490 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
3491 &mode, 8);
3492 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
3493 NULL, &parent, 8);
3494 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
3495 &fsize, 8);
3496 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
3497 acctm, 16);
3498 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
3499 modtm, 16);
3500 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
3501 crtm, 16);
3502 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
3503 chgtm, 16);
3504 SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
3505 &pflags, 8);
3507 if (sa_bulk_lookup(hdl, bulk, idx)) {
3508 (void) sa_handle_destroy(hdl);
3509 return;
3512 z_crtime = (time_t)crtm[0];
3513 z_atime = (time_t)acctm[0];
3514 z_mtime = (time_t)modtm[0];
3515 z_ctime = (time_t)chgtm[0];
3517 if (dump_opt['d'] > 4) {
3518 error = zfs_obj_to_path(os, object, path, sizeof (path));
3519 if (error == ESTALE) {
3520 (void) snprintf(path, sizeof (path), "on delete queue");
3521 } else if (error != 0) {
3522 leaked_objects++;
3523 (void) snprintf(path, sizeof (path),
3524 "path not found, possibly leaked");
3526 (void) printf("\tpath %s\n", path);
3529 if (S_ISLNK(mode))
3530 dump_znode_symlink(hdl);
3531 dump_uidgid(os, uid, gid);
3532 (void) printf("\tatime %s", ctime(&z_atime));
3533 (void) printf("\tmtime %s", ctime(&z_mtime));
3534 (void) printf("\tctime %s", ctime(&z_ctime));
3535 (void) printf("\tcrtime %s", ctime(&z_crtime));
3536 (void) printf("\tgen %llu\n", (u_longlong_t)gen);
3537 (void) printf("\tmode %llo\n", (u_longlong_t)mode);
3538 (void) printf("\tsize %llu\n", (u_longlong_t)fsize);
3539 (void) printf("\tparent %llu\n", (u_longlong_t)parent);
3540 (void) printf("\tlinks %llu\n", (u_longlong_t)links);
3541 (void) printf("\tpflags %llx\n", (u_longlong_t)pflags);
3542 if (dmu_objset_projectquota_enabled(os) && (pflags & ZFS_PROJID)) {
3543 uint64_t projid;
3545 if (sa_lookup(hdl, sa_attr_table[ZPL_PROJID], &projid,
3546 sizeof (uint64_t)) == 0)
3547 (void) printf("\tprojid %llu\n", (u_longlong_t)projid);
3549 if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
3550 sizeof (uint64_t)) == 0)
3551 (void) printf("\txattr %llu\n", (u_longlong_t)xattr);
3552 if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
3553 sizeof (uint64_t)) == 0)
3554 (void) printf("\trdev 0x%016llx\n", (u_longlong_t)rdev);
3555 dump_znode_sa_xattr(hdl);
3556 sa_handle_destroy(hdl);
3559 static void
3560 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
3562 (void) os, (void) object, (void) data, (void) size;
3565 static void
3566 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
3568 (void) os, (void) object, (void) data, (void) size;
3571 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
3572 dump_none, /* unallocated */
3573 dump_zap, /* object directory */
3574 dump_uint64, /* object array */
3575 dump_none, /* packed nvlist */
3576 dump_packed_nvlist, /* packed nvlist size */
3577 dump_none, /* bpobj */
3578 dump_bpobj, /* bpobj header */
3579 dump_none, /* SPA space map header */
3580 dump_none, /* SPA space map */
3581 dump_none, /* ZIL intent log */
3582 dump_dnode, /* DMU dnode */
3583 dump_dmu_objset, /* DMU objset */
3584 dump_dsl_dir, /* DSL directory */
3585 dump_zap, /* DSL directory child map */
3586 dump_zap, /* DSL dataset snap map */
3587 dump_zap, /* DSL props */
3588 dump_dsl_dataset, /* DSL dataset */
3589 dump_znode, /* ZFS znode */
3590 dump_acl, /* ZFS V0 ACL */
3591 dump_uint8, /* ZFS plain file */
3592 dump_zpldir, /* ZFS directory */
3593 dump_zap, /* ZFS master node */
3594 dump_zap, /* ZFS delete queue */
3595 dump_uint8, /* zvol object */
3596 dump_zap, /* zvol prop */
3597 dump_uint8, /* other uint8[] */
3598 dump_uint64, /* other uint64[] */
3599 dump_zap, /* other ZAP */
3600 dump_zap, /* persistent error log */
3601 dump_uint8, /* SPA history */
3602 dump_history_offsets, /* SPA history offsets */
3603 dump_zap, /* Pool properties */
3604 dump_zap, /* DSL permissions */
3605 dump_acl, /* ZFS ACL */
3606 dump_uint8, /* ZFS SYSACL */
3607 dump_none, /* FUID nvlist */
3608 dump_packed_nvlist, /* FUID nvlist size */
3609 dump_zap, /* DSL dataset next clones */
3610 dump_zap, /* DSL scrub queue */
3611 dump_zap, /* ZFS user/group/project used */
3612 dump_zap, /* ZFS user/group/project quota */
3613 dump_zap, /* snapshot refcount tags */
3614 dump_ddt_zap, /* DDT ZAP object */
3615 dump_zap, /* DDT statistics */
3616 dump_znode, /* SA object */
3617 dump_zap, /* SA Master Node */
3618 dump_sa_attrs, /* SA attribute registration */
3619 dump_sa_layouts, /* SA attribute layouts */
3620 dump_zap, /* DSL scrub translations */
3621 dump_none, /* fake dedup BP */
3622 dump_zap, /* deadlist */
3623 dump_none, /* deadlist hdr */
3624 dump_zap, /* dsl clones */
3625 dump_bpobj_subobjs, /* bpobj subobjs */
3626 dump_unknown, /* Unknown type, must be last */
3629 static boolean_t
3630 match_object_type(dmu_object_type_t obj_type, uint64_t flags)
3632 boolean_t match = B_TRUE;
3634 switch (obj_type) {
3635 case DMU_OT_DIRECTORY_CONTENTS:
3636 if (!(flags & ZOR_FLAG_DIRECTORY))
3637 match = B_FALSE;
3638 break;
3639 case DMU_OT_PLAIN_FILE_CONTENTS:
3640 if (!(flags & ZOR_FLAG_PLAIN_FILE))
3641 match = B_FALSE;
3642 break;
3643 case DMU_OT_SPACE_MAP:
3644 if (!(flags & ZOR_FLAG_SPACE_MAP))
3645 match = B_FALSE;
3646 break;
3647 default:
3648 if (strcmp(zdb_ot_name(obj_type), "zap") == 0) {
3649 if (!(flags & ZOR_FLAG_ZAP))
3650 match = B_FALSE;
3651 break;
3655 * If all bits except some of the supported flags are
3656 * set, the user combined the all-types flag (A) with
3657 * a negated flag to exclude some types (e.g. A-f to
3658 * show all object types except plain files).
3660 if ((flags | ZOR_SUPPORTED_FLAGS) != ZOR_FLAG_ALL_TYPES)
3661 match = B_FALSE;
3663 break;
3666 return (match);
3669 static void
3670 dump_object(objset_t *os, uint64_t object, int verbosity,
3671 boolean_t *print_header, uint64_t *dnode_slots_used, uint64_t flags)
3673 dmu_buf_t *db = NULL;
3674 dmu_object_info_t doi;
3675 dnode_t *dn;
3676 boolean_t dnode_held = B_FALSE;
3677 void *bonus = NULL;
3678 size_t bsize = 0;
3679 char iblk[32], dblk[32], lsize[32], asize[32], fill[32], dnsize[32];
3680 char bonus_size[32];
3681 char aux[50];
3682 int error;
3684 /* make sure nicenum has enough space */
3685 _Static_assert(sizeof (iblk) >= NN_NUMBUF_SZ, "iblk truncated");
3686 _Static_assert(sizeof (dblk) >= NN_NUMBUF_SZ, "dblk truncated");
3687 _Static_assert(sizeof (lsize) >= NN_NUMBUF_SZ, "lsize truncated");
3688 _Static_assert(sizeof (asize) >= NN_NUMBUF_SZ, "asize truncated");
3689 _Static_assert(sizeof (bonus_size) >= NN_NUMBUF_SZ,
3690 "bonus_size truncated");
3692 if (*print_header) {
3693 (void) printf("\n%10s %3s %5s %5s %5s %6s %5s %6s %s\n",
3694 "Object", "lvl", "iblk", "dblk", "dsize", "dnsize",
3695 "lsize", "%full", "type");
3696 *print_header = 0;
3699 if (object == 0) {
3700 dn = DMU_META_DNODE(os);
3701 dmu_object_info_from_dnode(dn, &doi);
3702 } else {
3704 * Encrypted datasets will have sensitive bonus buffers
3705 * encrypted. Therefore we cannot hold the bonus buffer and
3706 * must hold the dnode itself instead.
3708 error = dmu_object_info(os, object, &doi);
3709 if (error)
3710 fatal("dmu_object_info() failed, errno %u", error);
3712 if (!key_loaded && os->os_encrypted &&
3713 DMU_OT_IS_ENCRYPTED(doi.doi_bonus_type)) {
3714 error = dnode_hold(os, object, FTAG, &dn);
3715 if (error)
3716 fatal("dnode_hold() failed, errno %u", error);
3717 dnode_held = B_TRUE;
3718 } else {
3719 error = dmu_bonus_hold(os, object, FTAG, &db);
3720 if (error)
3721 fatal("dmu_bonus_hold(%llu) failed, errno %u",
3722 object, error);
3723 bonus = db->db_data;
3724 bsize = db->db_size;
3725 dn = DB_DNODE((dmu_buf_impl_t *)db);
3730 * Default to showing all object types if no flags were specified.
3732 if (flags != 0 && flags != ZOR_FLAG_ALL_TYPES &&
3733 !match_object_type(doi.doi_type, flags))
3734 goto out;
3736 if (dnode_slots_used)
3737 *dnode_slots_used = doi.doi_dnodesize / DNODE_MIN_SIZE;
3739 zdb_nicenum(doi.doi_metadata_block_size, iblk, sizeof (iblk));
3740 zdb_nicenum(doi.doi_data_block_size, dblk, sizeof (dblk));
3741 zdb_nicenum(doi.doi_max_offset, lsize, sizeof (lsize));
3742 zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize, sizeof (asize));
3743 zdb_nicenum(doi.doi_bonus_size, bonus_size, sizeof (bonus_size));
3744 zdb_nicenum(doi.doi_dnodesize, dnsize, sizeof (dnsize));
3745 (void) snprintf(fill, sizeof (fill), "%6.2f", 100.0 *
3746 doi.doi_fill_count * doi.doi_data_block_size / (object == 0 ?
3747 DNODES_PER_BLOCK : 1) / doi.doi_max_offset);
3749 aux[0] = '\0';
3751 if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
3752 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
3753 " (K=%s)", ZDB_CHECKSUM_NAME(doi.doi_checksum));
3756 if (doi.doi_compress == ZIO_COMPRESS_INHERIT &&
3757 ZIO_COMPRESS_HASLEVEL(os->os_compress) && verbosity >= 6) {
3758 const char *compname = NULL;
3759 if (zfs_prop_index_to_string(ZFS_PROP_COMPRESSION,
3760 ZIO_COMPRESS_RAW(os->os_compress, os->os_complevel),
3761 &compname) == 0) {
3762 (void) snprintf(aux + strlen(aux),
3763 sizeof (aux) - strlen(aux), " (Z=inherit=%s)",
3764 compname);
3765 } else {
3766 (void) snprintf(aux + strlen(aux),
3767 sizeof (aux) - strlen(aux),
3768 " (Z=inherit=%s-unknown)",
3769 ZDB_COMPRESS_NAME(os->os_compress));
3771 } else if (doi.doi_compress == ZIO_COMPRESS_INHERIT && verbosity >= 6) {
3772 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
3773 " (Z=inherit=%s)", ZDB_COMPRESS_NAME(os->os_compress));
3774 } else if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
3775 (void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
3776 " (Z=%s)", ZDB_COMPRESS_NAME(doi.doi_compress));
3779 (void) printf("%10lld %3u %5s %5s %5s %6s %5s %6s %s%s\n",
3780 (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
3781 asize, dnsize, lsize, fill, zdb_ot_name(doi.doi_type), aux);
3783 if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
3784 (void) printf("%10s %3s %5s %5s %5s %5s %5s %6s %s\n",
3785 "", "", "", "", "", "", bonus_size, "bonus",
3786 zdb_ot_name(doi.doi_bonus_type));
3789 if (verbosity >= 4) {
3790 (void) printf("\tdnode flags: %s%s%s%s\n",
3791 (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
3792 "USED_BYTES " : "",
3793 (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
3794 "USERUSED_ACCOUNTED " : "",
3795 (dn->dn_phys->dn_flags & DNODE_FLAG_USEROBJUSED_ACCOUNTED) ?
3796 "USEROBJUSED_ACCOUNTED " : "",
3797 (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
3798 "SPILL_BLKPTR" : "");
3799 (void) printf("\tdnode maxblkid: %llu\n",
3800 (longlong_t)dn->dn_phys->dn_maxblkid);
3802 if (!dnode_held) {
3803 object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os,
3804 object, bonus, bsize);
3805 } else {
3806 (void) printf("\t\t(bonus encrypted)\n");
3809 if (key_loaded ||
3810 (!os->os_encrypted || !DMU_OT_IS_ENCRYPTED(doi.doi_type))) {
3811 object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object,
3812 NULL, 0);
3813 } else {
3814 (void) printf("\t\t(object encrypted)\n");
3817 *print_header = B_TRUE;
3820 if (verbosity >= 5) {
3821 if (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
3822 char blkbuf[BP_SPRINTF_LEN];
3823 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf),
3824 DN_SPILL_BLKPTR(dn->dn_phys), B_FALSE);
3825 (void) printf("\nSpill block: %s\n", blkbuf);
3827 dump_indirect(dn);
3830 if (verbosity >= 5) {
3832 * Report the list of segments that comprise the object.
3834 uint64_t start = 0;
3835 uint64_t end;
3836 uint64_t blkfill = 1;
3837 int minlvl = 1;
3839 if (dn->dn_type == DMU_OT_DNODE) {
3840 minlvl = 0;
3841 blkfill = DNODES_PER_BLOCK;
3844 for (;;) {
3845 char segsize[32];
3846 /* make sure nicenum has enough space */
3847 _Static_assert(sizeof (segsize) >= NN_NUMBUF_SZ,
3848 "segsize truncated");
3849 error = dnode_next_offset(dn,
3850 0, &start, minlvl, blkfill, 0);
3851 if (error)
3852 break;
3853 end = start;
3854 error = dnode_next_offset(dn,
3855 DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
3856 zdb_nicenum(end - start, segsize, sizeof (segsize));
3857 (void) printf("\t\tsegment [%016llx, %016llx)"
3858 " size %5s\n", (u_longlong_t)start,
3859 (u_longlong_t)end, segsize);
3860 if (error)
3861 break;
3862 start = end;
3866 out:
3867 if (db != NULL)
3868 dmu_buf_rele(db, FTAG);
3869 if (dnode_held)
3870 dnode_rele(dn, FTAG);
3873 static void
3874 count_dir_mos_objects(dsl_dir_t *dd)
3876 mos_obj_refd(dd->dd_object);
3877 mos_obj_refd(dsl_dir_phys(dd)->dd_child_dir_zapobj);
3878 mos_obj_refd(dsl_dir_phys(dd)->dd_deleg_zapobj);
3879 mos_obj_refd(dsl_dir_phys(dd)->dd_props_zapobj);
3880 mos_obj_refd(dsl_dir_phys(dd)->dd_clones);
3883 * The dd_crypto_obj can be referenced by multiple dsl_dir's.
3884 * Ignore the references after the first one.
3886 mos_obj_refd_multiple(dd->dd_crypto_obj);
3889 static void
3890 count_ds_mos_objects(dsl_dataset_t *ds)
3892 mos_obj_refd(ds->ds_object);
3893 mos_obj_refd(dsl_dataset_phys(ds)->ds_next_clones_obj);
3894 mos_obj_refd(dsl_dataset_phys(ds)->ds_props_obj);
3895 mos_obj_refd(dsl_dataset_phys(ds)->ds_userrefs_obj);
3896 mos_obj_refd(dsl_dataset_phys(ds)->ds_snapnames_zapobj);
3897 mos_obj_refd(ds->ds_bookmarks_obj);
3899 if (!dsl_dataset_is_snapshot(ds)) {
3900 count_dir_mos_objects(ds->ds_dir);
3904 static const char *const objset_types[DMU_OST_NUMTYPES] = {
3905 "NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
3908 * Parse a string denoting a range of object IDs of the form
3909 * <start>[:<end>[:flags]], and store the results in zor.
3910 * Return 0 on success. On error, return 1 and update the msg
3911 * pointer to point to a descriptive error message.
3913 static int
3914 parse_object_range(char *range, zopt_object_range_t *zor, const char **msg)
3916 uint64_t flags = 0;
3917 char *p, *s, *dup, *flagstr, *tmp = NULL;
3918 size_t len;
3919 int i;
3920 int rc = 0;
3922 if (strchr(range, ':') == NULL) {
3923 zor->zor_obj_start = strtoull(range, &p, 0);
3924 if (*p != '\0') {
3925 *msg = "Invalid characters in object ID";
3926 rc = 1;
3928 zor->zor_obj_start = ZDB_MAP_OBJECT_ID(zor->zor_obj_start);
3929 zor->zor_obj_end = zor->zor_obj_start;
3930 return (rc);
3933 if (strchr(range, ':') == range) {
3934 *msg = "Invalid leading colon";
3935 rc = 1;
3936 return (rc);
3939 len = strlen(range);
3940 if (range[len - 1] == ':') {
3941 *msg = "Invalid trailing colon";
3942 rc = 1;
3943 return (rc);
3946 dup = strdup(range);
3947 s = strtok_r(dup, ":", &tmp);
3948 zor->zor_obj_start = strtoull(s, &p, 0);
3950 if (*p != '\0') {
3951 *msg = "Invalid characters in start object ID";
3952 rc = 1;
3953 goto out;
3956 s = strtok_r(NULL, ":", &tmp);
3957 zor->zor_obj_end = strtoull(s, &p, 0);
3959 if (*p != '\0') {
3960 *msg = "Invalid characters in end object ID";
3961 rc = 1;
3962 goto out;
3965 if (zor->zor_obj_start > zor->zor_obj_end) {
3966 *msg = "Start object ID may not exceed end object ID";
3967 rc = 1;
3968 goto out;
3971 s = strtok_r(NULL, ":", &tmp);
3972 if (s == NULL) {
3973 zor->zor_flags = ZOR_FLAG_ALL_TYPES;
3974 goto out;
3975 } else if (strtok_r(NULL, ":", &tmp) != NULL) {
3976 *msg = "Invalid colon-delimited field after flags";
3977 rc = 1;
3978 goto out;
3981 flagstr = s;
3982 for (i = 0; flagstr[i]; i++) {
3983 int bit;
3984 boolean_t negation = (flagstr[i] == '-');
3986 if (negation) {
3987 i++;
3988 if (flagstr[i] == '\0') {
3989 *msg = "Invalid trailing negation operator";
3990 rc = 1;
3991 goto out;
3994 bit = flagbits[(uchar_t)flagstr[i]];
3995 if (bit == 0) {
3996 *msg = "Invalid flag";
3997 rc = 1;
3998 goto out;
4000 if (negation)
4001 flags &= ~bit;
4002 else
4003 flags |= bit;
4005 zor->zor_flags = flags;
4007 zor->zor_obj_start = ZDB_MAP_OBJECT_ID(zor->zor_obj_start);
4008 zor->zor_obj_end = ZDB_MAP_OBJECT_ID(zor->zor_obj_end);
4010 out:
4011 free(dup);
4012 return (rc);
4015 static void
4016 dump_objset(objset_t *os)
4018 dmu_objset_stats_t dds = { 0 };
4019 uint64_t object, object_count;
4020 uint64_t refdbytes, usedobjs, scratch;
4021 char numbuf[32];
4022 char blkbuf[BP_SPRINTF_LEN + 20];
4023 char osname[ZFS_MAX_DATASET_NAME_LEN];
4024 const char *type = "UNKNOWN";
4025 int verbosity = dump_opt['d'];
4026 boolean_t print_header;
4027 unsigned i;
4028 int error;
4029 uint64_t total_slots_used = 0;
4030 uint64_t max_slot_used = 0;
4031 uint64_t dnode_slots;
4032 uint64_t obj_start;
4033 uint64_t obj_end;
4034 uint64_t flags;
4036 /* make sure nicenum has enough space */
4037 _Static_assert(sizeof (numbuf) >= NN_NUMBUF_SZ, "numbuf truncated");
4039 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
4040 dmu_objset_fast_stat(os, &dds);
4041 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
4043 print_header = B_TRUE;
4045 if (dds.dds_type < DMU_OST_NUMTYPES)
4046 type = objset_types[dds.dds_type];
4048 if (dds.dds_type == DMU_OST_META) {
4049 dds.dds_creation_txg = TXG_INITIAL;
4050 usedobjs = BP_GET_FILL(os->os_rootbp);
4051 refdbytes = dsl_dir_phys(os->os_spa->spa_dsl_pool->dp_mos_dir)->
4052 dd_used_bytes;
4053 } else {
4054 dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
4057 ASSERT3U(usedobjs, ==, BP_GET_FILL(os->os_rootbp));
4059 zdb_nicenum(refdbytes, numbuf, sizeof (numbuf));
4061 if (verbosity >= 4) {
4062 (void) snprintf(blkbuf, sizeof (blkbuf), ", rootbp ");
4063 (void) snprintf_blkptr(blkbuf + strlen(blkbuf),
4064 sizeof (blkbuf) - strlen(blkbuf), os->os_rootbp);
4065 } else {
4066 blkbuf[0] = '\0';
4069 dmu_objset_name(os, osname);
4071 (void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
4072 "%s, %llu objects%s%s\n",
4073 osname, type, (u_longlong_t)dmu_objset_id(os),
4074 (u_longlong_t)dds.dds_creation_txg,
4075 numbuf, (u_longlong_t)usedobjs, blkbuf,
4076 (dds.dds_inconsistent) ? " (inconsistent)" : "");
4078 for (i = 0; i < zopt_object_args; i++) {
4079 obj_start = zopt_object_ranges[i].zor_obj_start;
4080 obj_end = zopt_object_ranges[i].zor_obj_end;
4081 flags = zopt_object_ranges[i].zor_flags;
4083 object = obj_start;
4084 if (object == 0 || obj_start == obj_end)
4085 dump_object(os, object, verbosity, &print_header, NULL,
4086 flags);
4087 else
4088 object--;
4090 while ((dmu_object_next(os, &object, B_FALSE, 0) == 0) &&
4091 object <= obj_end) {
4092 dump_object(os, object, verbosity, &print_header, NULL,
4093 flags);
4097 if (zopt_object_args > 0) {
4098 (void) printf("\n");
4099 return;
4102 if (dump_opt['i'] != 0 || verbosity >= 2)
4103 dump_intent_log(dmu_objset_zil(os));
4105 if (dmu_objset_ds(os) != NULL) {
4106 dsl_dataset_t *ds = dmu_objset_ds(os);
4107 dump_blkptr_list(&ds->ds_deadlist, "Deadlist");
4108 if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist) &&
4109 !dmu_objset_is_snapshot(os)) {
4110 dump_blkptr_list(&ds->ds_dir->dd_livelist, "Livelist");
4111 if (verify_dd_livelist(os) != 0)
4112 fatal("livelist is incorrect");
4115 if (dsl_dataset_remap_deadlist_exists(ds)) {
4116 (void) printf("ds_remap_deadlist:\n");
4117 dump_blkptr_list(&ds->ds_remap_deadlist, "Deadlist");
4119 count_ds_mos_objects(ds);
4122 if (dmu_objset_ds(os) != NULL)
4123 dump_bookmarks(os, verbosity);
4125 if (verbosity < 2)
4126 return;
4128 if (BP_IS_HOLE(os->os_rootbp))
4129 return;
4131 dump_object(os, 0, verbosity, &print_header, NULL, 0);
4132 object_count = 0;
4133 if (DMU_USERUSED_DNODE(os) != NULL &&
4134 DMU_USERUSED_DNODE(os)->dn_type != 0) {
4135 dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header,
4136 NULL, 0);
4137 dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header,
4138 NULL, 0);
4141 if (DMU_PROJECTUSED_DNODE(os) != NULL &&
4142 DMU_PROJECTUSED_DNODE(os)->dn_type != 0)
4143 dump_object(os, DMU_PROJECTUSED_OBJECT, verbosity,
4144 &print_header, NULL, 0);
4146 object = 0;
4147 while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
4148 dump_object(os, object, verbosity, &print_header, &dnode_slots,
4150 object_count++;
4151 total_slots_used += dnode_slots;
4152 max_slot_used = object + dnode_slots - 1;
4155 (void) printf("\n");
4157 (void) printf(" Dnode slots:\n");
4158 (void) printf("\tTotal used: %10llu\n",
4159 (u_longlong_t)total_slots_used);
4160 (void) printf("\tMax used: %10llu\n",
4161 (u_longlong_t)max_slot_used);
4162 (void) printf("\tPercent empty: %10lf\n",
4163 (double)(max_slot_used - total_slots_used)*100 /
4164 (double)max_slot_used);
4165 (void) printf("\n");
4167 if (error != ESRCH) {
4168 (void) fprintf(stderr, "dmu_object_next() = %d\n", error);
4169 abort();
4172 ASSERT3U(object_count, ==, usedobjs);
4174 if (leaked_objects != 0) {
4175 (void) printf("%d potentially leaked objects detected\n",
4176 leaked_objects);
4177 leaked_objects = 0;
4181 static void
4182 dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
4184 time_t timestamp = ub->ub_timestamp;
4186 (void) printf("%s", header ? header : "");
4187 (void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
4188 (void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
4189 (void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
4190 (void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
4191 (void) printf("\ttimestamp = %llu UTC = %s",
4192 (u_longlong_t)ub->ub_timestamp, ctime(&timestamp));
4194 (void) printf("\tmmp_magic = %016llx\n",
4195 (u_longlong_t)ub->ub_mmp_magic);
4196 if (MMP_VALID(ub)) {
4197 (void) printf("\tmmp_delay = %0llu\n",
4198 (u_longlong_t)ub->ub_mmp_delay);
4199 if (MMP_SEQ_VALID(ub))
4200 (void) printf("\tmmp_seq = %u\n",
4201 (unsigned int) MMP_SEQ(ub));
4202 if (MMP_FAIL_INT_VALID(ub))
4203 (void) printf("\tmmp_fail = %u\n",
4204 (unsigned int) MMP_FAIL_INT(ub));
4205 if (MMP_INTERVAL_VALID(ub))
4206 (void) printf("\tmmp_write = %u\n",
4207 (unsigned int) MMP_INTERVAL(ub));
4208 /* After MMP_* to make summarize_uberblock_mmp cleaner */
4209 (void) printf("\tmmp_valid = %x\n",
4210 (unsigned int) ub->ub_mmp_config & 0xFF);
4213 if (dump_opt['u'] >= 4) {
4214 char blkbuf[BP_SPRINTF_LEN];
4215 snprintf_blkptr(blkbuf, sizeof (blkbuf), &ub->ub_rootbp);
4216 (void) printf("\trootbp = %s\n", blkbuf);
4218 (void) printf("\tcheckpoint_txg = %llu\n",
4219 (u_longlong_t)ub->ub_checkpoint_txg);
4220 (void) printf("%s", footer ? footer : "");
4223 static void
4224 dump_config(spa_t *spa)
4226 dmu_buf_t *db;
4227 size_t nvsize = 0;
4228 int error = 0;
4231 error = dmu_bonus_hold(spa->spa_meta_objset,
4232 spa->spa_config_object, FTAG, &db);
4234 if (error == 0) {
4235 nvsize = *(uint64_t *)db->db_data;
4236 dmu_buf_rele(db, FTAG);
4238 (void) printf("\nMOS Configuration:\n");
4239 dump_packed_nvlist(spa->spa_meta_objset,
4240 spa->spa_config_object, (void *)&nvsize, 1);
4241 } else {
4242 (void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
4243 (u_longlong_t)spa->spa_config_object, error);
4247 static void
4248 dump_cachefile(const char *cachefile)
4250 int fd;
4251 struct stat64 statbuf;
4252 char *buf;
4253 nvlist_t *config;
4255 if ((fd = open64(cachefile, O_RDONLY)) < 0) {
4256 (void) printf("cannot open '%s': %s\n", cachefile,
4257 strerror(errno));
4258 exit(1);
4261 if (fstat64(fd, &statbuf) != 0) {
4262 (void) printf("failed to stat '%s': %s\n", cachefile,
4263 strerror(errno));
4264 exit(1);
4267 if ((buf = malloc(statbuf.st_size)) == NULL) {
4268 (void) fprintf(stderr, "failed to allocate %llu bytes\n",
4269 (u_longlong_t)statbuf.st_size);
4270 exit(1);
4273 if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
4274 (void) fprintf(stderr, "failed to read %llu bytes\n",
4275 (u_longlong_t)statbuf.st_size);
4276 exit(1);
4279 (void) close(fd);
4281 if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
4282 (void) fprintf(stderr, "failed to unpack nvlist\n");
4283 exit(1);
4286 free(buf);
4288 dump_nvlist(config, 0);
4290 nvlist_free(config);
4294 * ZFS label nvlist stats
4296 typedef struct zdb_nvl_stats {
4297 int zns_list_count;
4298 int zns_leaf_count;
4299 size_t zns_leaf_largest;
4300 size_t zns_leaf_total;
4301 nvlist_t *zns_string;
4302 nvlist_t *zns_uint64;
4303 nvlist_t *zns_boolean;
4304 } zdb_nvl_stats_t;
4306 static void
4307 collect_nvlist_stats(nvlist_t *nvl, zdb_nvl_stats_t *stats)
4309 nvlist_t *list, **array;
4310 nvpair_t *nvp = NULL;
4311 const char *name;
4312 uint_t i, items;
4314 stats->zns_list_count++;
4316 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4317 name = nvpair_name(nvp);
4319 switch (nvpair_type(nvp)) {
4320 case DATA_TYPE_STRING:
4321 fnvlist_add_string(stats->zns_string, name,
4322 fnvpair_value_string(nvp));
4323 break;
4324 case DATA_TYPE_UINT64:
4325 fnvlist_add_uint64(stats->zns_uint64, name,
4326 fnvpair_value_uint64(nvp));
4327 break;
4328 case DATA_TYPE_BOOLEAN:
4329 fnvlist_add_boolean(stats->zns_boolean, name);
4330 break;
4331 case DATA_TYPE_NVLIST:
4332 if (nvpair_value_nvlist(nvp, &list) == 0)
4333 collect_nvlist_stats(list, stats);
4334 break;
4335 case DATA_TYPE_NVLIST_ARRAY:
4336 if (nvpair_value_nvlist_array(nvp, &array, &items) != 0)
4337 break;
4339 for (i = 0; i < items; i++) {
4340 collect_nvlist_stats(array[i], stats);
4342 /* collect stats on leaf vdev */
4343 if (strcmp(name, "children") == 0) {
4344 size_t size;
4346 (void) nvlist_size(array[i], &size,
4347 NV_ENCODE_XDR);
4348 stats->zns_leaf_total += size;
4349 if (size > stats->zns_leaf_largest)
4350 stats->zns_leaf_largest = size;
4351 stats->zns_leaf_count++;
4354 break;
4355 default:
4356 (void) printf("skip type %d!\n", (int)nvpair_type(nvp));
4361 static void
4362 dump_nvlist_stats(nvlist_t *nvl, size_t cap)
4364 zdb_nvl_stats_t stats = { 0 };
4365 size_t size, sum = 0, total;
4366 size_t noise;
4368 /* requires nvlist with non-unique names for stat collection */
4369 VERIFY0(nvlist_alloc(&stats.zns_string, 0, 0));
4370 VERIFY0(nvlist_alloc(&stats.zns_uint64, 0, 0));
4371 VERIFY0(nvlist_alloc(&stats.zns_boolean, 0, 0));
4372 VERIFY0(nvlist_size(stats.zns_boolean, &noise, NV_ENCODE_XDR));
4374 (void) printf("\n\nZFS Label NVList Config Stats:\n");
4376 VERIFY0(nvlist_size(nvl, &total, NV_ENCODE_XDR));
4377 (void) printf(" %d bytes used, %d bytes free (using %4.1f%%)\n\n",
4378 (int)total, (int)(cap - total), 100.0 * total / cap);
4380 collect_nvlist_stats(nvl, &stats);
4382 VERIFY0(nvlist_size(stats.zns_uint64, &size, NV_ENCODE_XDR));
4383 size -= noise;
4384 sum += size;
4385 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "integers:",
4386 (int)fnvlist_num_pairs(stats.zns_uint64),
4387 (int)size, 100.0 * size / total);
4389 VERIFY0(nvlist_size(stats.zns_string, &size, NV_ENCODE_XDR));
4390 size -= noise;
4391 sum += size;
4392 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "strings:",
4393 (int)fnvlist_num_pairs(stats.zns_string),
4394 (int)size, 100.0 * size / total);
4396 VERIFY0(nvlist_size(stats.zns_boolean, &size, NV_ENCODE_XDR));
4397 size -= noise;
4398 sum += size;
4399 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "booleans:",
4400 (int)fnvlist_num_pairs(stats.zns_boolean),
4401 (int)size, 100.0 * size / total);
4403 size = total - sum; /* treat remainder as nvlist overhead */
4404 (void) printf("%12s %4d %6d bytes (%5.2f%%)\n\n", "nvlists:",
4405 stats.zns_list_count, (int)size, 100.0 * size / total);
4407 if (stats.zns_leaf_count > 0) {
4408 size_t average = stats.zns_leaf_total / stats.zns_leaf_count;
4410 (void) printf("%12s %4d %6d bytes average\n", "leaf vdevs:",
4411 stats.zns_leaf_count, (int)average);
4412 (void) printf("%24d bytes largest\n",
4413 (int)stats.zns_leaf_largest);
4415 if (dump_opt['l'] >= 3 && average > 0)
4416 (void) printf(" space for %d additional leaf vdevs\n",
4417 (int)((cap - total) / average));
4419 (void) printf("\n");
4421 nvlist_free(stats.zns_string);
4422 nvlist_free(stats.zns_uint64);
4423 nvlist_free(stats.zns_boolean);
4426 typedef struct cksum_record {
4427 zio_cksum_t cksum;
4428 boolean_t labels[VDEV_LABELS];
4429 avl_node_t link;
4430 } cksum_record_t;
4432 static int
4433 cksum_record_compare(const void *x1, const void *x2)
4435 const cksum_record_t *l = (cksum_record_t *)x1;
4436 const cksum_record_t *r = (cksum_record_t *)x2;
4437 int arraysize = ARRAY_SIZE(l->cksum.zc_word);
4438 int difference = 0;
4440 for (int i = 0; i < arraysize; i++) {
4441 difference = TREE_CMP(l->cksum.zc_word[i], r->cksum.zc_word[i]);
4442 if (difference)
4443 break;
4446 return (difference);
4449 static cksum_record_t *
4450 cksum_record_alloc(zio_cksum_t *cksum, int l)
4452 cksum_record_t *rec;
4454 rec = umem_zalloc(sizeof (*rec), UMEM_NOFAIL);
4455 rec->cksum = *cksum;
4456 rec->labels[l] = B_TRUE;
4458 return (rec);
4461 static cksum_record_t *
4462 cksum_record_lookup(avl_tree_t *tree, zio_cksum_t *cksum)
4464 cksum_record_t lookup = { .cksum = *cksum };
4465 avl_index_t where;
4467 return (avl_find(tree, &lookup, &where));
4470 static cksum_record_t *
4471 cksum_record_insert(avl_tree_t *tree, zio_cksum_t *cksum, int l)
4473 cksum_record_t *rec;
4475 rec = cksum_record_lookup(tree, cksum);
4476 if (rec) {
4477 rec->labels[l] = B_TRUE;
4478 } else {
4479 rec = cksum_record_alloc(cksum, l);
4480 avl_add(tree, rec);
4483 return (rec);
4486 static int
4487 first_label(cksum_record_t *rec)
4489 for (int i = 0; i < VDEV_LABELS; i++)
4490 if (rec->labels[i])
4491 return (i);
4493 return (-1);
4496 static void
4497 print_label_numbers(const char *prefix, const cksum_record_t *rec)
4499 fputs(prefix, stdout);
4500 for (int i = 0; i < VDEV_LABELS; i++)
4501 if (rec->labels[i] == B_TRUE)
4502 printf("%d ", i);
4503 putchar('\n');
4506 #define MAX_UBERBLOCK_COUNT (VDEV_UBERBLOCK_RING >> UBERBLOCK_SHIFT)
4508 typedef struct zdb_label {
4509 vdev_label_t label;
4510 uint64_t label_offset;
4511 nvlist_t *config_nv;
4512 cksum_record_t *config;
4513 cksum_record_t *uberblocks[MAX_UBERBLOCK_COUNT];
4514 boolean_t header_printed;
4515 boolean_t read_failed;
4516 boolean_t cksum_valid;
4517 } zdb_label_t;
4519 static void
4520 print_label_header(zdb_label_t *label, int l)
4523 if (dump_opt['q'])
4524 return;
4526 if (label->header_printed == B_TRUE)
4527 return;
4529 (void) printf("------------------------------------\n");
4530 (void) printf("LABEL %d %s\n", l,
4531 label->cksum_valid ? "" : "(Bad label cksum)");
4532 (void) printf("------------------------------------\n");
4534 label->header_printed = B_TRUE;
4537 static void
4538 print_l2arc_header(void)
4540 (void) printf("------------------------------------\n");
4541 (void) printf("L2ARC device header\n");
4542 (void) printf("------------------------------------\n");
4545 static void
4546 print_l2arc_log_blocks(void)
4548 (void) printf("------------------------------------\n");
4549 (void) printf("L2ARC device log blocks\n");
4550 (void) printf("------------------------------------\n");
4553 static void
4554 dump_l2arc_log_entries(uint64_t log_entries,
4555 l2arc_log_ent_phys_t *le, uint64_t i)
4557 for (int j = 0; j < log_entries; j++) {
4558 dva_t dva = le[j].le_dva;
4559 (void) printf("lb[%4llu]\tle[%4d]\tDVA asize: %llu, "
4560 "vdev: %llu, offset: %llu\n",
4561 (u_longlong_t)i, j + 1,
4562 (u_longlong_t)DVA_GET_ASIZE(&dva),
4563 (u_longlong_t)DVA_GET_VDEV(&dva),
4564 (u_longlong_t)DVA_GET_OFFSET(&dva));
4565 (void) printf("|\t\t\t\tbirth: %llu\n",
4566 (u_longlong_t)le[j].le_birth);
4567 (void) printf("|\t\t\t\tlsize: %llu\n",
4568 (u_longlong_t)L2BLK_GET_LSIZE((&le[j])->le_prop));
4569 (void) printf("|\t\t\t\tpsize: %llu\n",
4570 (u_longlong_t)L2BLK_GET_PSIZE((&le[j])->le_prop));
4571 (void) printf("|\t\t\t\tcompr: %llu\n",
4572 (u_longlong_t)L2BLK_GET_COMPRESS((&le[j])->le_prop));
4573 (void) printf("|\t\t\t\tcomplevel: %llu\n",
4574 (u_longlong_t)(&le[j])->le_complevel);
4575 (void) printf("|\t\t\t\ttype: %llu\n",
4576 (u_longlong_t)L2BLK_GET_TYPE((&le[j])->le_prop));
4577 (void) printf("|\t\t\t\tprotected: %llu\n",
4578 (u_longlong_t)L2BLK_GET_PROTECTED((&le[j])->le_prop));
4579 (void) printf("|\t\t\t\tprefetch: %llu\n",
4580 (u_longlong_t)L2BLK_GET_PREFETCH((&le[j])->le_prop));
4581 (void) printf("|\t\t\t\taddress: %llu\n",
4582 (u_longlong_t)le[j].le_daddr);
4583 (void) printf("|\t\t\t\tARC state: %llu\n",
4584 (u_longlong_t)L2BLK_GET_STATE((&le[j])->le_prop));
4585 (void) printf("|\n");
4587 (void) printf("\n");
4590 static void
4591 dump_l2arc_log_blkptr(const l2arc_log_blkptr_t *lbps)
4593 (void) printf("|\t\tdaddr: %llu\n", (u_longlong_t)lbps->lbp_daddr);
4594 (void) printf("|\t\tpayload_asize: %llu\n",
4595 (u_longlong_t)lbps->lbp_payload_asize);
4596 (void) printf("|\t\tpayload_start: %llu\n",
4597 (u_longlong_t)lbps->lbp_payload_start);
4598 (void) printf("|\t\tlsize: %llu\n",
4599 (u_longlong_t)L2BLK_GET_LSIZE(lbps->lbp_prop));
4600 (void) printf("|\t\tasize: %llu\n",
4601 (u_longlong_t)L2BLK_GET_PSIZE(lbps->lbp_prop));
4602 (void) printf("|\t\tcompralgo: %llu\n",
4603 (u_longlong_t)L2BLK_GET_COMPRESS(lbps->lbp_prop));
4604 (void) printf("|\t\tcksumalgo: %llu\n",
4605 (u_longlong_t)L2BLK_GET_CHECKSUM(lbps->lbp_prop));
4606 (void) printf("|\n\n");
4609 static void
4610 dump_l2arc_log_blocks(int fd, const l2arc_dev_hdr_phys_t *l2dhdr,
4611 l2arc_dev_hdr_phys_t *rebuild)
4613 l2arc_log_blk_phys_t this_lb;
4614 uint64_t asize;
4615 l2arc_log_blkptr_t lbps[2];
4616 abd_t *abd;
4617 zio_cksum_t cksum;
4618 int failed = 0;
4619 l2arc_dev_t dev;
4621 if (!dump_opt['q'])
4622 print_l2arc_log_blocks();
4623 memcpy(lbps, l2dhdr->dh_start_lbps, sizeof (lbps));
4625 dev.l2ad_evict = l2dhdr->dh_evict;
4626 dev.l2ad_start = l2dhdr->dh_start;
4627 dev.l2ad_end = l2dhdr->dh_end;
4629 if (l2dhdr->dh_start_lbps[0].lbp_daddr == 0) {
4630 /* no log blocks to read */
4631 if (!dump_opt['q']) {
4632 (void) printf("No log blocks to read\n");
4633 (void) printf("\n");
4635 return;
4636 } else {
4637 dev.l2ad_hand = lbps[0].lbp_daddr +
4638 L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
4641 dev.l2ad_first = !!(l2dhdr->dh_flags & L2ARC_DEV_HDR_EVICT_FIRST);
4643 for (;;) {
4644 if (!l2arc_log_blkptr_valid(&dev, &lbps[0]))
4645 break;
4647 /* L2BLK_GET_PSIZE returns aligned size for log blocks */
4648 asize = L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
4649 if (pread64(fd, &this_lb, asize, lbps[0].lbp_daddr) != asize) {
4650 if (!dump_opt['q']) {
4651 (void) printf("Error while reading next log "
4652 "block\n\n");
4654 break;
4657 fletcher_4_native_varsize(&this_lb, asize, &cksum);
4658 if (!ZIO_CHECKSUM_EQUAL(cksum, lbps[0].lbp_cksum)) {
4659 failed++;
4660 if (!dump_opt['q']) {
4661 (void) printf("Invalid cksum\n");
4662 dump_l2arc_log_blkptr(&lbps[0]);
4664 break;
4667 switch (L2BLK_GET_COMPRESS((&lbps[0])->lbp_prop)) {
4668 case ZIO_COMPRESS_OFF:
4669 break;
4670 default:
4671 abd = abd_alloc_for_io(asize, B_TRUE);
4672 abd_copy_from_buf_off(abd, &this_lb, 0, asize);
4673 if (zio_decompress_data(L2BLK_GET_COMPRESS(
4674 (&lbps[0])->lbp_prop), abd, &this_lb,
4675 asize, sizeof (this_lb), NULL) != 0) {
4676 (void) printf("L2ARC block decompression "
4677 "failed\n");
4678 abd_free(abd);
4679 goto out;
4681 abd_free(abd);
4682 break;
4685 if (this_lb.lb_magic == BSWAP_64(L2ARC_LOG_BLK_MAGIC))
4686 byteswap_uint64_array(&this_lb, sizeof (this_lb));
4687 if (this_lb.lb_magic != L2ARC_LOG_BLK_MAGIC) {
4688 if (!dump_opt['q'])
4689 (void) printf("Invalid log block magic\n\n");
4690 break;
4693 rebuild->dh_lb_count++;
4694 rebuild->dh_lb_asize += asize;
4695 if (dump_opt['l'] > 1 && !dump_opt['q']) {
4696 (void) printf("lb[%4llu]\tmagic: %llu\n",
4697 (u_longlong_t)rebuild->dh_lb_count,
4698 (u_longlong_t)this_lb.lb_magic);
4699 dump_l2arc_log_blkptr(&lbps[0]);
4702 if (dump_opt['l'] > 2 && !dump_opt['q'])
4703 dump_l2arc_log_entries(l2dhdr->dh_log_entries,
4704 this_lb.lb_entries,
4705 rebuild->dh_lb_count);
4707 if (l2arc_range_check_overlap(lbps[1].lbp_payload_start,
4708 lbps[0].lbp_payload_start, dev.l2ad_evict) &&
4709 !dev.l2ad_first)
4710 break;
4712 lbps[0] = lbps[1];
4713 lbps[1] = this_lb.lb_prev_lbp;
4715 out:
4716 if (!dump_opt['q']) {
4717 (void) printf("log_blk_count:\t %llu with valid cksum\n",
4718 (u_longlong_t)rebuild->dh_lb_count);
4719 (void) printf("\t\t %d with invalid cksum\n", failed);
4720 (void) printf("log_blk_asize:\t %llu\n\n",
4721 (u_longlong_t)rebuild->dh_lb_asize);
4725 static int
4726 dump_l2arc_header(int fd)
4728 l2arc_dev_hdr_phys_t l2dhdr = {0}, rebuild = {0};
4729 int error = B_FALSE;
4731 if (pread64(fd, &l2dhdr, sizeof (l2dhdr),
4732 VDEV_LABEL_START_SIZE) != sizeof (l2dhdr)) {
4733 error = B_TRUE;
4734 } else {
4735 if (l2dhdr.dh_magic == BSWAP_64(L2ARC_DEV_HDR_MAGIC))
4736 byteswap_uint64_array(&l2dhdr, sizeof (l2dhdr));
4738 if (l2dhdr.dh_magic != L2ARC_DEV_HDR_MAGIC)
4739 error = B_TRUE;
4742 if (error) {
4743 (void) printf("L2ARC device header not found\n\n");
4744 /* Do not return an error here for backward compatibility */
4745 return (0);
4746 } else if (!dump_opt['q']) {
4747 print_l2arc_header();
4749 (void) printf(" magic: %llu\n",
4750 (u_longlong_t)l2dhdr.dh_magic);
4751 (void) printf(" version: %llu\n",
4752 (u_longlong_t)l2dhdr.dh_version);
4753 (void) printf(" pool_guid: %llu\n",
4754 (u_longlong_t)l2dhdr.dh_spa_guid);
4755 (void) printf(" flags: %llu\n",
4756 (u_longlong_t)l2dhdr.dh_flags);
4757 (void) printf(" start_lbps[0]: %llu\n",
4758 (u_longlong_t)
4759 l2dhdr.dh_start_lbps[0].lbp_daddr);
4760 (void) printf(" start_lbps[1]: %llu\n",
4761 (u_longlong_t)
4762 l2dhdr.dh_start_lbps[1].lbp_daddr);
4763 (void) printf(" log_blk_ent: %llu\n",
4764 (u_longlong_t)l2dhdr.dh_log_entries);
4765 (void) printf(" start: %llu\n",
4766 (u_longlong_t)l2dhdr.dh_start);
4767 (void) printf(" end: %llu\n",
4768 (u_longlong_t)l2dhdr.dh_end);
4769 (void) printf(" evict: %llu\n",
4770 (u_longlong_t)l2dhdr.dh_evict);
4771 (void) printf(" lb_asize_refcount: %llu\n",
4772 (u_longlong_t)l2dhdr.dh_lb_asize);
4773 (void) printf(" lb_count_refcount: %llu\n",
4774 (u_longlong_t)l2dhdr.dh_lb_count);
4775 (void) printf(" trim_action_time: %llu\n",
4776 (u_longlong_t)l2dhdr.dh_trim_action_time);
4777 (void) printf(" trim_state: %llu\n\n",
4778 (u_longlong_t)l2dhdr.dh_trim_state);
4781 dump_l2arc_log_blocks(fd, &l2dhdr, &rebuild);
4783 * The total aligned size of log blocks and the number of log blocks
4784 * reported in the header of the device may be less than what zdb
4785 * reports by dump_l2arc_log_blocks() which emulates l2arc_rebuild().
4786 * This happens because dump_l2arc_log_blocks() lacks the memory
4787 * pressure valve that l2arc_rebuild() has. Thus, if we are on a system
4788 * with low memory, l2arc_rebuild will exit prematurely and dh_lb_asize
4789 * and dh_lb_count will be lower to begin with than what exists on the
4790 * device. This is normal and zdb should not exit with an error. The
4791 * opposite case should never happen though, the values reported in the
4792 * header should never be higher than what dump_l2arc_log_blocks() and
4793 * l2arc_rebuild() report. If this happens there is a leak in the
4794 * accounting of log blocks.
4796 if (l2dhdr.dh_lb_asize > rebuild.dh_lb_asize ||
4797 l2dhdr.dh_lb_count > rebuild.dh_lb_count)
4798 return (1);
4800 return (0);
4803 static void
4804 dump_config_from_label(zdb_label_t *label, size_t buflen, int l)
4806 if (dump_opt['q'])
4807 return;
4809 if ((dump_opt['l'] < 3) && (first_label(label->config) != l))
4810 return;
4812 print_label_header(label, l);
4813 dump_nvlist(label->config_nv, 4);
4814 print_label_numbers(" labels = ", label->config);
4816 if (dump_opt['l'] >= 2)
4817 dump_nvlist_stats(label->config_nv, buflen);
4820 #define ZDB_MAX_UB_HEADER_SIZE 32
4822 static void
4823 dump_label_uberblocks(zdb_label_t *label, uint64_t ashift, int label_num)
4826 vdev_t vd;
4827 char header[ZDB_MAX_UB_HEADER_SIZE];
4829 vd.vdev_ashift = ashift;
4830 vd.vdev_top = &vd;
4832 for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
4833 uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
4834 uberblock_t *ub = (void *)((char *)&label->label + uoff);
4835 cksum_record_t *rec = label->uberblocks[i];
4837 if (rec == NULL) {
4838 if (dump_opt['u'] >= 2) {
4839 print_label_header(label, label_num);
4840 (void) printf(" Uberblock[%d] invalid\n", i);
4842 continue;
4845 if ((dump_opt['u'] < 3) && (first_label(rec) != label_num))
4846 continue;
4848 if ((dump_opt['u'] < 4) &&
4849 (ub->ub_mmp_magic == MMP_MAGIC) && ub->ub_mmp_delay &&
4850 (i >= VDEV_UBERBLOCK_COUNT(&vd) - MMP_BLOCKS_PER_LABEL))
4851 continue;
4853 print_label_header(label, label_num);
4854 (void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
4855 " Uberblock[%d]\n", i);
4856 dump_uberblock(ub, header, "");
4857 print_label_numbers(" labels = ", rec);
4861 static char curpath[PATH_MAX];
4864 * Iterate through the path components, recursively passing
4865 * current one's obj and remaining path until we find the obj
4866 * for the last one.
4868 static int
4869 dump_path_impl(objset_t *os, uint64_t obj, char *name, uint64_t *retobj)
4871 int err;
4872 boolean_t header = B_TRUE;
4873 uint64_t child_obj;
4874 char *s;
4875 dmu_buf_t *db;
4876 dmu_object_info_t doi;
4878 if ((s = strchr(name, '/')) != NULL)
4879 *s = '\0';
4880 err = zap_lookup(os, obj, name, 8, 1, &child_obj);
4882 (void) strlcat(curpath, name, sizeof (curpath));
4884 if (err != 0) {
4885 (void) fprintf(stderr, "failed to lookup %s: %s\n",
4886 curpath, strerror(err));
4887 return (err);
4890 child_obj = ZFS_DIRENT_OBJ(child_obj);
4891 err = sa_buf_hold(os, child_obj, FTAG, &db);
4892 if (err != 0) {
4893 (void) fprintf(stderr,
4894 "failed to get SA dbuf for obj %llu: %s\n",
4895 (u_longlong_t)child_obj, strerror(err));
4896 return (EINVAL);
4898 dmu_object_info_from_db(db, &doi);
4899 sa_buf_rele(db, FTAG);
4901 if (doi.doi_bonus_type != DMU_OT_SA &&
4902 doi.doi_bonus_type != DMU_OT_ZNODE) {
4903 (void) fprintf(stderr, "invalid bonus type %d for obj %llu\n",
4904 doi.doi_bonus_type, (u_longlong_t)child_obj);
4905 return (EINVAL);
4908 if (dump_opt['v'] > 6) {
4909 (void) printf("obj=%llu %s type=%d bonustype=%d\n",
4910 (u_longlong_t)child_obj, curpath, doi.doi_type,
4911 doi.doi_bonus_type);
4914 (void) strlcat(curpath, "/", sizeof (curpath));
4916 switch (doi.doi_type) {
4917 case DMU_OT_DIRECTORY_CONTENTS:
4918 if (s != NULL && *(s + 1) != '\0')
4919 return (dump_path_impl(os, child_obj, s + 1, retobj));
4920 zfs_fallthrough;
4921 case DMU_OT_PLAIN_FILE_CONTENTS:
4922 if (retobj != NULL) {
4923 *retobj = child_obj;
4924 } else {
4925 dump_object(os, child_obj, dump_opt['v'], &header,
4926 NULL, 0);
4928 return (0);
4929 default:
4930 (void) fprintf(stderr, "object %llu has non-file/directory "
4931 "type %d\n", (u_longlong_t)obj, doi.doi_type);
4932 break;
4935 return (EINVAL);
4939 * Dump the blocks for the object specified by path inside the dataset.
4941 static int
4942 dump_path(char *ds, char *path, uint64_t *retobj)
4944 int err;
4945 objset_t *os;
4946 uint64_t root_obj;
4948 err = open_objset(ds, FTAG, &os);
4949 if (err != 0)
4950 return (err);
4952 err = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1, &root_obj);
4953 if (err != 0) {
4954 (void) fprintf(stderr, "can't lookup root znode: %s\n",
4955 strerror(err));
4956 close_objset(os, FTAG);
4957 return (EINVAL);
4960 (void) snprintf(curpath, sizeof (curpath), "dataset=%s path=/", ds);
4962 err = dump_path_impl(os, root_obj, path, retobj);
4964 close_objset(os, FTAG);
4965 return (err);
4968 static int
4969 dump_backup_bytes(objset_t *os, void *buf, int len, void *arg)
4971 const char *p = (const char *)buf;
4972 ssize_t nwritten;
4974 (void) os;
4975 (void) arg;
4977 /* Write the data out, handling short writes and signals. */
4978 while ((nwritten = write(STDOUT_FILENO, p, len)) < len) {
4979 if (nwritten < 0) {
4980 if (errno == EINTR)
4981 continue;
4982 return (errno);
4984 p += nwritten;
4985 len -= nwritten;
4988 return (0);
4991 static void
4992 dump_backup(const char *pool, uint64_t objset_id, const char *flagstr)
4994 boolean_t embed = B_FALSE;
4995 boolean_t large_block = B_FALSE;
4996 boolean_t compress = B_FALSE;
4997 boolean_t raw = B_FALSE;
4999 const char *c;
5000 for (c = flagstr; c != NULL && *c != '\0'; c++) {
5001 switch (*c) {
5002 case 'e':
5003 embed = B_TRUE;
5004 break;
5005 case 'L':
5006 large_block = B_TRUE;
5007 break;
5008 case 'c':
5009 compress = B_TRUE;
5010 break;
5011 case 'w':
5012 raw = B_TRUE;
5013 break;
5014 default:
5015 fprintf(stderr, "dump_backup: invalid flag "
5016 "'%c'\n", *c);
5017 return;
5021 if (isatty(STDOUT_FILENO)) {
5022 fprintf(stderr, "dump_backup: stream cannot be written "
5023 "to a terminal\n");
5024 return;
5027 offset_t off = 0;
5028 dmu_send_outparams_t out = {
5029 .dso_outfunc = dump_backup_bytes,
5030 .dso_dryrun = B_FALSE,
5033 int err = dmu_send_obj(pool, objset_id, /* fromsnap */0, embed,
5034 large_block, compress, raw, /* saved */ B_FALSE, STDOUT_FILENO,
5035 &off, &out);
5036 if (err != 0) {
5037 fprintf(stderr, "dump_backup: dmu_send_obj: %s\n",
5038 strerror(err));
5039 return;
5043 static int
5044 zdb_copy_object(objset_t *os, uint64_t srcobj, char *destfile)
5046 int err = 0;
5047 uint64_t size, readsize, oursize, offset;
5048 ssize_t writesize;
5049 sa_handle_t *hdl;
5051 (void) printf("Copying object %" PRIu64 " to file %s\n", srcobj,
5052 destfile);
5054 VERIFY3P(os, ==, sa_os);
5055 if ((err = sa_handle_get(os, srcobj, NULL, SA_HDL_PRIVATE, &hdl))) {
5056 (void) printf("Failed to get handle for SA znode\n");
5057 return (err);
5059 if ((err = sa_lookup(hdl, sa_attr_table[ZPL_SIZE], &size, 8))) {
5060 (void) sa_handle_destroy(hdl);
5061 return (err);
5063 (void) sa_handle_destroy(hdl);
5065 (void) printf("Object %" PRIu64 " is %" PRIu64 " bytes\n", srcobj,
5066 size);
5067 if (size == 0) {
5068 return (EINVAL);
5071 int fd = open(destfile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
5072 if (fd == -1)
5073 return (errno);
5075 * We cap the size at 1 mebibyte here to prevent
5076 * allocation failures and nigh-infinite printing if the
5077 * object is extremely large.
5079 oursize = MIN(size, 1 << 20);
5080 offset = 0;
5081 char *buf = kmem_alloc(oursize, KM_NOSLEEP);
5082 if (buf == NULL) {
5083 (void) close(fd);
5084 return (ENOMEM);
5087 while (offset < size) {
5088 readsize = MIN(size - offset, 1 << 20);
5089 err = dmu_read(os, srcobj, offset, readsize, buf, 0);
5090 if (err != 0) {
5091 (void) printf("got error %u from dmu_read\n", err);
5092 kmem_free(buf, oursize);
5093 (void) close(fd);
5094 return (err);
5096 if (dump_opt['v'] > 3) {
5097 (void) printf("Read offset=%" PRIu64 " size=%" PRIu64
5098 " error=%d\n", offset, readsize, err);
5101 writesize = write(fd, buf, readsize);
5102 if (writesize < 0) {
5103 err = errno;
5104 break;
5105 } else if (writesize != readsize) {
5106 /* Incomplete write */
5107 (void) fprintf(stderr, "Short write, only wrote %llu of"
5108 " %" PRIu64 " bytes, exiting...\n",
5109 (u_longlong_t)writesize, readsize);
5110 break;
5113 offset += readsize;
5116 (void) close(fd);
5118 if (buf != NULL)
5119 kmem_free(buf, oursize);
5121 return (err);
5124 static boolean_t
5125 label_cksum_valid(vdev_label_t *label, uint64_t offset)
5127 zio_checksum_info_t *ci = &zio_checksum_table[ZIO_CHECKSUM_LABEL];
5128 zio_cksum_t expected_cksum;
5129 zio_cksum_t actual_cksum;
5130 zio_cksum_t verifier;
5131 zio_eck_t *eck;
5132 int byteswap;
5134 void *data = (char *)label + offsetof(vdev_label_t, vl_vdev_phys);
5135 eck = (zio_eck_t *)((char *)(data) + VDEV_PHYS_SIZE) - 1;
5137 offset += offsetof(vdev_label_t, vl_vdev_phys);
5138 ZIO_SET_CHECKSUM(&verifier, offset, 0, 0, 0);
5140 byteswap = (eck->zec_magic == BSWAP_64(ZEC_MAGIC));
5141 if (byteswap)
5142 byteswap_uint64_array(&verifier, sizeof (zio_cksum_t));
5144 expected_cksum = eck->zec_cksum;
5145 eck->zec_cksum = verifier;
5147 abd_t *abd = abd_get_from_buf(data, VDEV_PHYS_SIZE);
5148 ci->ci_func[byteswap](abd, VDEV_PHYS_SIZE, NULL, &actual_cksum);
5149 abd_free(abd);
5151 if (byteswap)
5152 byteswap_uint64_array(&expected_cksum, sizeof (zio_cksum_t));
5154 if (ZIO_CHECKSUM_EQUAL(actual_cksum, expected_cksum))
5155 return (B_TRUE);
5157 return (B_FALSE);
5160 static int
5161 dump_label(const char *dev)
5163 char path[MAXPATHLEN];
5164 zdb_label_t labels[VDEV_LABELS] = {{{{0}}}};
5165 uint64_t psize, ashift, l2cache;
5166 struct stat64 statbuf;
5167 boolean_t config_found = B_FALSE;
5168 boolean_t error = B_FALSE;
5169 boolean_t read_l2arc_header = B_FALSE;
5170 avl_tree_t config_tree;
5171 avl_tree_t uberblock_tree;
5172 void *node, *cookie;
5173 int fd;
5176 * Check if we were given absolute path and use it as is.
5177 * Otherwise if the provided vdev name doesn't point to a file,
5178 * try prepending expected disk paths and partition numbers.
5180 (void) strlcpy(path, dev, sizeof (path));
5181 if (dev[0] != '/' && stat64(path, &statbuf) != 0) {
5182 int error;
5184 error = zfs_resolve_shortname(dev, path, MAXPATHLEN);
5185 if (error == 0 && zfs_dev_is_whole_disk(path)) {
5186 if (zfs_append_partition(path, MAXPATHLEN) == -1)
5187 error = ENOENT;
5190 if (error || (stat64(path, &statbuf) != 0)) {
5191 (void) printf("failed to find device %s, try "
5192 "specifying absolute path instead\n", dev);
5193 return (1);
5197 if ((fd = open64(path, O_RDONLY)) < 0) {
5198 (void) printf("cannot open '%s': %s\n", path, strerror(errno));
5199 exit(1);
5202 if (fstat64_blk(fd, &statbuf) != 0) {
5203 (void) printf("failed to stat '%s': %s\n", path,
5204 strerror(errno));
5205 (void) close(fd);
5206 exit(1);
5209 if (S_ISBLK(statbuf.st_mode) && zfs_dev_flush(fd) != 0)
5210 (void) printf("failed to invalidate cache '%s' : %s\n", path,
5211 strerror(errno));
5213 avl_create(&config_tree, cksum_record_compare,
5214 sizeof (cksum_record_t), offsetof(cksum_record_t, link));
5215 avl_create(&uberblock_tree, cksum_record_compare,
5216 sizeof (cksum_record_t), offsetof(cksum_record_t, link));
5218 psize = statbuf.st_size;
5219 psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
5220 ashift = SPA_MINBLOCKSHIFT;
5223 * 1. Read the label from disk
5224 * 2. Verify label cksum
5225 * 3. Unpack the configuration and insert in config tree.
5226 * 4. Traverse all uberblocks and insert in uberblock tree.
5228 for (int l = 0; l < VDEV_LABELS; l++) {
5229 zdb_label_t *label = &labels[l];
5230 char *buf = label->label.vl_vdev_phys.vp_nvlist;
5231 size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
5232 nvlist_t *config;
5233 cksum_record_t *rec;
5234 zio_cksum_t cksum;
5235 vdev_t vd;
5237 label->label_offset = vdev_label_offset(psize, l, 0);
5239 if (pread64(fd, &label->label, sizeof (label->label),
5240 label->label_offset) != sizeof (label->label)) {
5241 if (!dump_opt['q'])
5242 (void) printf("failed to read label %d\n", l);
5243 label->read_failed = B_TRUE;
5244 error = B_TRUE;
5245 continue;
5248 label->read_failed = B_FALSE;
5249 label->cksum_valid = label_cksum_valid(&label->label,
5250 label->label_offset);
5252 if (nvlist_unpack(buf, buflen, &config, 0) == 0) {
5253 nvlist_t *vdev_tree = NULL;
5254 size_t size;
5256 if ((nvlist_lookup_nvlist(config,
5257 ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
5258 (nvlist_lookup_uint64(vdev_tree,
5259 ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
5260 ashift = SPA_MINBLOCKSHIFT;
5262 if (nvlist_size(config, &size, NV_ENCODE_XDR) != 0)
5263 size = buflen;
5265 /* If the device is a cache device read the header. */
5266 if (!read_l2arc_header) {
5267 if (nvlist_lookup_uint64(config,
5268 ZPOOL_CONFIG_POOL_STATE, &l2cache) == 0 &&
5269 l2cache == POOL_STATE_L2CACHE) {
5270 read_l2arc_header = B_TRUE;
5274 fletcher_4_native_varsize(buf, size, &cksum);
5275 rec = cksum_record_insert(&config_tree, &cksum, l);
5277 label->config = rec;
5278 label->config_nv = config;
5279 config_found = B_TRUE;
5280 } else {
5281 error = B_TRUE;
5284 vd.vdev_ashift = ashift;
5285 vd.vdev_top = &vd;
5287 for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
5288 uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
5289 uberblock_t *ub = (void *)((char *)label + uoff);
5291 if (uberblock_verify(ub))
5292 continue;
5294 fletcher_4_native_varsize(ub, sizeof (*ub), &cksum);
5295 rec = cksum_record_insert(&uberblock_tree, &cksum, l);
5297 label->uberblocks[i] = rec;
5302 * Dump the label and uberblocks.
5304 for (int l = 0; l < VDEV_LABELS; l++) {
5305 zdb_label_t *label = &labels[l];
5306 size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
5308 if (label->read_failed == B_TRUE)
5309 continue;
5311 if (label->config_nv) {
5312 dump_config_from_label(label, buflen, l);
5313 } else {
5314 if (!dump_opt['q'])
5315 (void) printf("failed to unpack label %d\n", l);
5318 if (dump_opt['u'])
5319 dump_label_uberblocks(label, ashift, l);
5321 nvlist_free(label->config_nv);
5325 * Dump the L2ARC header, if existent.
5327 if (read_l2arc_header)
5328 error |= dump_l2arc_header(fd);
5330 cookie = NULL;
5331 while ((node = avl_destroy_nodes(&config_tree, &cookie)) != NULL)
5332 umem_free(node, sizeof (cksum_record_t));
5334 cookie = NULL;
5335 while ((node = avl_destroy_nodes(&uberblock_tree, &cookie)) != NULL)
5336 umem_free(node, sizeof (cksum_record_t));
5338 avl_destroy(&config_tree);
5339 avl_destroy(&uberblock_tree);
5341 (void) close(fd);
5343 return (config_found == B_FALSE ? 2 :
5344 (error == B_TRUE ? 1 : 0));
5347 static uint64_t dataset_feature_count[SPA_FEATURES];
5348 static uint64_t global_feature_count[SPA_FEATURES];
5349 static uint64_t remap_deadlist_count = 0;
5351 static int
5352 dump_one_objset(const char *dsname, void *arg)
5354 (void) arg;
5355 int error;
5356 objset_t *os;
5357 spa_feature_t f;
5359 error = open_objset(dsname, FTAG, &os);
5360 if (error != 0)
5361 return (0);
5363 for (f = 0; f < SPA_FEATURES; f++) {
5364 if (!dsl_dataset_feature_is_active(dmu_objset_ds(os), f))
5365 continue;
5366 ASSERT(spa_feature_table[f].fi_flags &
5367 ZFEATURE_FLAG_PER_DATASET);
5368 dataset_feature_count[f]++;
5371 if (dsl_dataset_remap_deadlist_exists(dmu_objset_ds(os))) {
5372 remap_deadlist_count++;
5375 for (dsl_bookmark_node_t *dbn =
5376 avl_first(&dmu_objset_ds(os)->ds_bookmarks); dbn != NULL;
5377 dbn = AVL_NEXT(&dmu_objset_ds(os)->ds_bookmarks, dbn)) {
5378 mos_obj_refd(dbn->dbn_phys.zbm_redaction_obj);
5379 if (dbn->dbn_phys.zbm_redaction_obj != 0)
5380 global_feature_count[SPA_FEATURE_REDACTION_BOOKMARKS]++;
5381 if (dbn->dbn_phys.zbm_flags & ZBM_FLAG_HAS_FBN)
5382 global_feature_count[SPA_FEATURE_BOOKMARK_WRITTEN]++;
5385 if (dsl_deadlist_is_open(&dmu_objset_ds(os)->ds_dir->dd_livelist) &&
5386 !dmu_objset_is_snapshot(os)) {
5387 global_feature_count[SPA_FEATURE_LIVELIST]++;
5390 dump_objset(os);
5391 close_objset(os, FTAG);
5392 fuid_table_destroy();
5393 return (0);
5397 * Block statistics.
5399 #define PSIZE_HISTO_SIZE (SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 2)
5400 typedef struct zdb_blkstats {
5401 uint64_t zb_asize;
5402 uint64_t zb_lsize;
5403 uint64_t zb_psize;
5404 uint64_t zb_count;
5405 uint64_t zb_gangs;
5406 uint64_t zb_ditto_samevdev;
5407 uint64_t zb_ditto_same_ms;
5408 uint64_t zb_psize_histogram[PSIZE_HISTO_SIZE];
5409 } zdb_blkstats_t;
5412 * Extended object types to report deferred frees and dedup auto-ditto blocks.
5414 #define ZDB_OT_DEFERRED (DMU_OT_NUMTYPES + 0)
5415 #define ZDB_OT_DITTO (DMU_OT_NUMTYPES + 1)
5416 #define ZDB_OT_OTHER (DMU_OT_NUMTYPES + 2)
5417 #define ZDB_OT_TOTAL (DMU_OT_NUMTYPES + 3)
5419 static const char *zdb_ot_extname[] = {
5420 "deferred free",
5421 "dedup ditto",
5422 "other",
5423 "Total",
5426 #define ZB_TOTAL DN_MAX_LEVELS
5427 #define SPA_MAX_FOR_16M (SPA_MAXBLOCKSHIFT+1)
5429 typedef struct zdb_brt_entry {
5430 dva_t zbre_dva;
5431 uint64_t zbre_refcount;
5432 avl_node_t zbre_node;
5433 } zdb_brt_entry_t;
5435 typedef struct zdb_cb {
5436 zdb_blkstats_t zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
5437 uint64_t zcb_removing_size;
5438 uint64_t zcb_checkpoint_size;
5439 uint64_t zcb_dedup_asize;
5440 uint64_t zcb_dedup_blocks;
5441 uint64_t zcb_clone_asize;
5442 uint64_t zcb_clone_blocks;
5443 uint64_t zcb_psize_count[SPA_MAX_FOR_16M];
5444 uint64_t zcb_lsize_count[SPA_MAX_FOR_16M];
5445 uint64_t zcb_asize_count[SPA_MAX_FOR_16M];
5446 uint64_t zcb_psize_len[SPA_MAX_FOR_16M];
5447 uint64_t zcb_lsize_len[SPA_MAX_FOR_16M];
5448 uint64_t zcb_asize_len[SPA_MAX_FOR_16M];
5449 uint64_t zcb_psize_total;
5450 uint64_t zcb_lsize_total;
5451 uint64_t zcb_asize_total;
5452 uint64_t zcb_embedded_blocks[NUM_BP_EMBEDDED_TYPES];
5453 uint64_t zcb_embedded_histogram[NUM_BP_EMBEDDED_TYPES]
5454 [BPE_PAYLOAD_SIZE + 1];
5455 uint64_t zcb_start;
5456 hrtime_t zcb_lastprint;
5457 uint64_t zcb_totalasize;
5458 uint64_t zcb_errors[256];
5459 int zcb_readfails;
5460 int zcb_haderrors;
5461 spa_t *zcb_spa;
5462 uint32_t **zcb_vd_obsolete_counts;
5463 avl_tree_t zcb_brt;
5464 boolean_t zcb_brt_is_active;
5465 } zdb_cb_t;
5467 /* test if two DVA offsets from same vdev are within the same metaslab */
5468 static boolean_t
5469 same_metaslab(spa_t *spa, uint64_t vdev, uint64_t off1, uint64_t off2)
5471 vdev_t *vd = vdev_lookup_top(spa, vdev);
5472 uint64_t ms_shift = vd->vdev_ms_shift;
5474 return ((off1 >> ms_shift) == (off2 >> ms_shift));
5478 * Used to simplify reporting of the histogram data.
5480 typedef struct one_histo {
5481 const char *name;
5482 uint64_t *count;
5483 uint64_t *len;
5484 uint64_t cumulative;
5485 } one_histo_t;
5488 * The number of separate histograms processed for psize, lsize and asize.
5490 #define NUM_HISTO 3
5493 * This routine will create a fixed column size output of three different
5494 * histograms showing by blocksize of 512 - 2^ SPA_MAX_FOR_16M
5495 * the count, length and cumulative length of the psize, lsize and
5496 * asize blocks.
5498 * All three types of blocks are listed on a single line
5500 * By default the table is printed in nicenumber format (e.g. 123K) but
5501 * if the '-P' parameter is specified then the full raw number (parseable)
5502 * is printed out.
5504 static void
5505 dump_size_histograms(zdb_cb_t *zcb)
5508 * A temporary buffer that allows us to convert a number into
5509 * a string using zdb_nicenumber to allow either raw or human
5510 * readable numbers to be output.
5512 char numbuf[32];
5515 * Define titles which are used in the headers of the tables
5516 * printed by this routine.
5518 const char blocksize_title1[] = "block";
5519 const char blocksize_title2[] = "size";
5520 const char count_title[] = "Count";
5521 const char length_title[] = "Size";
5522 const char cumulative_title[] = "Cum.";
5525 * Setup the histogram arrays (psize, lsize, and asize).
5527 one_histo_t parm_histo[NUM_HISTO];
5529 parm_histo[0].name = "psize";
5530 parm_histo[0].count = zcb->zcb_psize_count;
5531 parm_histo[0].len = zcb->zcb_psize_len;
5532 parm_histo[0].cumulative = 0;
5534 parm_histo[1].name = "lsize";
5535 parm_histo[1].count = zcb->zcb_lsize_count;
5536 parm_histo[1].len = zcb->zcb_lsize_len;
5537 parm_histo[1].cumulative = 0;
5539 parm_histo[2].name = "asize";
5540 parm_histo[2].count = zcb->zcb_asize_count;
5541 parm_histo[2].len = zcb->zcb_asize_len;
5542 parm_histo[2].cumulative = 0;
5545 (void) printf("\nBlock Size Histogram\n");
5547 * Print the first line titles
5549 if (dump_opt['P'])
5550 (void) printf("\n%s\t", blocksize_title1);
5551 else
5552 (void) printf("\n%7s ", blocksize_title1);
5554 for (int j = 0; j < NUM_HISTO; j++) {
5555 if (dump_opt['P']) {
5556 if (j < NUM_HISTO - 1) {
5557 (void) printf("%s\t\t\t", parm_histo[j].name);
5558 } else {
5559 /* Don't print trailing spaces */
5560 (void) printf(" %s", parm_histo[j].name);
5562 } else {
5563 if (j < NUM_HISTO - 1) {
5564 /* Left aligned strings in the output */
5565 (void) printf("%-7s ",
5566 parm_histo[j].name);
5567 } else {
5568 /* Don't print trailing spaces */
5569 (void) printf("%s", parm_histo[j].name);
5573 (void) printf("\n");
5576 * Print the second line titles
5578 if (dump_opt['P']) {
5579 (void) printf("%s\t", blocksize_title2);
5580 } else {
5581 (void) printf("%7s ", blocksize_title2);
5584 for (int i = 0; i < NUM_HISTO; i++) {
5585 if (dump_opt['P']) {
5586 (void) printf("%s\t%s\t%s\t",
5587 count_title, length_title, cumulative_title);
5588 } else {
5589 (void) printf("%7s%7s%7s",
5590 count_title, length_title, cumulative_title);
5593 (void) printf("\n");
5596 * Print the rows
5598 for (int i = SPA_MINBLOCKSHIFT; i < SPA_MAX_FOR_16M; i++) {
5601 * Print the first column showing the blocksize
5603 zdb_nicenum((1ULL << i), numbuf, sizeof (numbuf));
5605 if (dump_opt['P']) {
5606 printf("%s", numbuf);
5607 } else {
5608 printf("%7s:", numbuf);
5612 * Print the remaining set of 3 columns per size:
5613 * for psize, lsize and asize
5615 for (int j = 0; j < NUM_HISTO; j++) {
5616 parm_histo[j].cumulative += parm_histo[j].len[i];
5618 zdb_nicenum(parm_histo[j].count[i],
5619 numbuf, sizeof (numbuf));
5620 if (dump_opt['P'])
5621 (void) printf("\t%s", numbuf);
5622 else
5623 (void) printf("%7s", numbuf);
5625 zdb_nicenum(parm_histo[j].len[i],
5626 numbuf, sizeof (numbuf));
5627 if (dump_opt['P'])
5628 (void) printf("\t%s", numbuf);
5629 else
5630 (void) printf("%7s", numbuf);
5632 zdb_nicenum(parm_histo[j].cumulative,
5633 numbuf, sizeof (numbuf));
5634 if (dump_opt['P'])
5635 (void) printf("\t%s", numbuf);
5636 else
5637 (void) printf("%7s", numbuf);
5639 (void) printf("\n");
5643 static void
5644 zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
5645 dmu_object_type_t type)
5647 uint64_t refcnt = 0;
5648 int i;
5650 ASSERT(type < ZDB_OT_TOTAL);
5652 if (zilog && zil_bp_tree_add(zilog, bp) != 0)
5653 return;
5655 spa_config_enter(zcb->zcb_spa, SCL_CONFIG, FTAG, RW_READER);
5657 for (i = 0; i < 4; i++) {
5658 int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
5659 int t = (i & 1) ? type : ZDB_OT_TOTAL;
5660 int equal;
5661 zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
5663 zb->zb_asize += BP_GET_ASIZE(bp);
5664 zb->zb_lsize += BP_GET_LSIZE(bp);
5665 zb->zb_psize += BP_GET_PSIZE(bp);
5666 zb->zb_count++;
5669 * The histogram is only big enough to record blocks up to
5670 * SPA_OLD_MAXBLOCKSIZE; larger blocks go into the last,
5671 * "other", bucket.
5673 unsigned idx = BP_GET_PSIZE(bp) >> SPA_MINBLOCKSHIFT;
5674 idx = MIN(idx, SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 1);
5675 zb->zb_psize_histogram[idx]++;
5677 zb->zb_gangs += BP_COUNT_GANG(bp);
5679 switch (BP_GET_NDVAS(bp)) {
5680 case 2:
5681 if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5682 DVA_GET_VDEV(&bp->blk_dva[1])) {
5683 zb->zb_ditto_samevdev++;
5685 if (same_metaslab(zcb->zcb_spa,
5686 DVA_GET_VDEV(&bp->blk_dva[0]),
5687 DVA_GET_OFFSET(&bp->blk_dva[0]),
5688 DVA_GET_OFFSET(&bp->blk_dva[1])))
5689 zb->zb_ditto_same_ms++;
5691 break;
5692 case 3:
5693 equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5694 DVA_GET_VDEV(&bp->blk_dva[1])) +
5695 (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5696 DVA_GET_VDEV(&bp->blk_dva[2])) +
5697 (DVA_GET_VDEV(&bp->blk_dva[1]) ==
5698 DVA_GET_VDEV(&bp->blk_dva[2]));
5699 if (equal != 0) {
5700 zb->zb_ditto_samevdev++;
5702 if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5703 DVA_GET_VDEV(&bp->blk_dva[1]) &&
5704 same_metaslab(zcb->zcb_spa,
5705 DVA_GET_VDEV(&bp->blk_dva[0]),
5706 DVA_GET_OFFSET(&bp->blk_dva[0]),
5707 DVA_GET_OFFSET(&bp->blk_dva[1])))
5708 zb->zb_ditto_same_ms++;
5709 else if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5710 DVA_GET_VDEV(&bp->blk_dva[2]) &&
5711 same_metaslab(zcb->zcb_spa,
5712 DVA_GET_VDEV(&bp->blk_dva[0]),
5713 DVA_GET_OFFSET(&bp->blk_dva[0]),
5714 DVA_GET_OFFSET(&bp->blk_dva[2])))
5715 zb->zb_ditto_same_ms++;
5716 else if (DVA_GET_VDEV(&bp->blk_dva[1]) ==
5717 DVA_GET_VDEV(&bp->blk_dva[2]) &&
5718 same_metaslab(zcb->zcb_spa,
5719 DVA_GET_VDEV(&bp->blk_dva[1]),
5720 DVA_GET_OFFSET(&bp->blk_dva[1]),
5721 DVA_GET_OFFSET(&bp->blk_dva[2])))
5722 zb->zb_ditto_same_ms++;
5724 break;
5728 spa_config_exit(zcb->zcb_spa, SCL_CONFIG, FTAG);
5730 if (BP_IS_EMBEDDED(bp)) {
5731 zcb->zcb_embedded_blocks[BPE_GET_ETYPE(bp)]++;
5732 zcb->zcb_embedded_histogram[BPE_GET_ETYPE(bp)]
5733 [BPE_GET_PSIZE(bp)]++;
5734 return;
5737 * The binning histogram bins by powers of two up to
5738 * SPA_MAXBLOCKSIZE rather than creating bins for
5739 * every possible blocksize found in the pool.
5741 int bin = highbit64(BP_GET_PSIZE(bp)) - 1;
5743 zcb->zcb_psize_count[bin]++;
5744 zcb->zcb_psize_len[bin] += BP_GET_PSIZE(bp);
5745 zcb->zcb_psize_total += BP_GET_PSIZE(bp);
5747 bin = highbit64(BP_GET_LSIZE(bp)) - 1;
5749 zcb->zcb_lsize_count[bin]++;
5750 zcb->zcb_lsize_len[bin] += BP_GET_LSIZE(bp);
5751 zcb->zcb_lsize_total += BP_GET_LSIZE(bp);
5753 bin = highbit64(BP_GET_ASIZE(bp)) - 1;
5755 zcb->zcb_asize_count[bin]++;
5756 zcb->zcb_asize_len[bin] += BP_GET_ASIZE(bp);
5757 zcb->zcb_asize_total += BP_GET_ASIZE(bp);
5759 if (zcb->zcb_brt_is_active && brt_maybe_exists(zcb->zcb_spa, bp)) {
5761 * Cloned blocks are special. We need to count them, so we can
5762 * later uncount them when reporting leaked space, and we must
5763 * only claim them them once.
5765 * To do this, we keep our own in-memory BRT. For each block
5766 * we haven't seen before, we look it up in the real BRT and
5767 * if its there, we note it and its refcount then proceed as
5768 * normal. If we see the block again, we count it as a clone
5769 * and then give it no further consideration.
5771 zdb_brt_entry_t zbre_search, *zbre;
5772 avl_index_t where;
5774 zbre_search.zbre_dva = bp->blk_dva[0];
5775 zbre = avl_find(&zcb->zcb_brt, &zbre_search, &where);
5776 if (zbre != NULL) {
5777 zcb->zcb_clone_asize += BP_GET_ASIZE(bp);
5778 zcb->zcb_clone_blocks++;
5780 zbre->zbre_refcount--;
5781 if (zbre->zbre_refcount == 0) {
5782 avl_remove(&zcb->zcb_brt, zbre);
5783 umem_free(zbre, sizeof (zdb_brt_entry_t));
5785 return;
5788 uint64_t crefcnt = brt_entry_get_refcount(zcb->zcb_spa, bp);
5789 if (crefcnt > 0) {
5790 zbre = umem_zalloc(sizeof (zdb_brt_entry_t),
5791 UMEM_NOFAIL);
5792 zbre->zbre_dva = bp->blk_dva[0];
5793 zbre->zbre_refcount = crefcnt;
5794 avl_insert(&zcb->zcb_brt, zbre, where);
5798 if (dump_opt['L'])
5799 return;
5801 if (BP_GET_DEDUP(bp)) {
5802 ddt_t *ddt;
5803 ddt_entry_t *dde;
5805 ddt = ddt_select(zcb->zcb_spa, bp);
5806 ddt_enter(ddt);
5807 dde = ddt_lookup(ddt, bp, B_FALSE);
5809 if (dde == NULL) {
5810 refcnt = 0;
5811 } else {
5812 ddt_phys_t *ddp = ddt_phys_select(dde, bp);
5813 ddt_phys_decref(ddp);
5814 refcnt = ddp->ddp_refcnt;
5815 if (ddt_phys_total_refcnt(dde) == 0)
5816 ddt_remove(ddt, dde);
5818 ddt_exit(ddt);
5821 VERIFY3U(zio_wait(zio_claim(NULL, zcb->zcb_spa,
5822 refcnt ? 0 : spa_min_claim_txg(zcb->zcb_spa),
5823 bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
5826 static void
5827 zdb_blkptr_done(zio_t *zio)
5829 spa_t *spa = zio->io_spa;
5830 blkptr_t *bp = zio->io_bp;
5831 int ioerr = zio->io_error;
5832 zdb_cb_t *zcb = zio->io_private;
5833 zbookmark_phys_t *zb = &zio->io_bookmark;
5835 mutex_enter(&spa->spa_scrub_lock);
5836 spa->spa_load_verify_bytes -= BP_GET_PSIZE(bp);
5837 cv_broadcast(&spa->spa_scrub_io_cv);
5839 if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
5840 char blkbuf[BP_SPRINTF_LEN];
5842 zcb->zcb_haderrors = 1;
5843 zcb->zcb_errors[ioerr]++;
5845 if (dump_opt['b'] >= 2)
5846 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
5847 else
5848 blkbuf[0] = '\0';
5850 (void) printf("zdb_blkptr_cb: "
5851 "Got error %d reading "
5852 "<%llu, %llu, %lld, %llx> %s -- skipping\n",
5853 ioerr,
5854 (u_longlong_t)zb->zb_objset,
5855 (u_longlong_t)zb->zb_object,
5856 (u_longlong_t)zb->zb_level,
5857 (u_longlong_t)zb->zb_blkid,
5858 blkbuf);
5860 mutex_exit(&spa->spa_scrub_lock);
5862 abd_free(zio->io_abd);
5865 static int
5866 zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
5867 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
5869 zdb_cb_t *zcb = arg;
5870 dmu_object_type_t type;
5871 boolean_t is_metadata;
5873 if (zb->zb_level == ZB_DNODE_LEVEL)
5874 return (0);
5876 if (dump_opt['b'] >= 5 && bp->blk_birth > 0) {
5877 char blkbuf[BP_SPRINTF_LEN];
5878 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
5879 (void) printf("objset %llu object %llu "
5880 "level %lld offset 0x%llx %s\n",
5881 (u_longlong_t)zb->zb_objset,
5882 (u_longlong_t)zb->zb_object,
5883 (longlong_t)zb->zb_level,
5884 (u_longlong_t)blkid2offset(dnp, bp, zb),
5885 blkbuf);
5888 if (BP_IS_HOLE(bp) || BP_IS_REDACTED(bp))
5889 return (0);
5891 type = BP_GET_TYPE(bp);
5893 zdb_count_block(zcb, zilog, bp,
5894 (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
5896 is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
5898 if (!BP_IS_EMBEDDED(bp) &&
5899 (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata))) {
5900 size_t size = BP_GET_PSIZE(bp);
5901 abd_t *abd = abd_alloc(size, B_FALSE);
5902 int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
5904 /* If it's an intent log block, failure is expected. */
5905 if (zb->zb_level == ZB_ZIL_LEVEL)
5906 flags |= ZIO_FLAG_SPECULATIVE;
5908 mutex_enter(&spa->spa_scrub_lock);
5909 while (spa->spa_load_verify_bytes > max_inflight_bytes)
5910 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
5911 spa->spa_load_verify_bytes += size;
5912 mutex_exit(&spa->spa_scrub_lock);
5914 zio_nowait(zio_read(NULL, spa, bp, abd, size,
5915 zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
5918 zcb->zcb_readfails = 0;
5920 /* only call gethrtime() every 100 blocks */
5921 static int iters;
5922 if (++iters > 100)
5923 iters = 0;
5924 else
5925 return (0);
5927 if (dump_opt['b'] < 5 && gethrtime() > zcb->zcb_lastprint + NANOSEC) {
5928 uint64_t now = gethrtime();
5929 char buf[10];
5930 uint64_t bytes = zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL].zb_asize;
5931 uint64_t kb_per_sec =
5932 1 + bytes / (1 + ((now - zcb->zcb_start) / 1000 / 1000));
5933 uint64_t sec_remaining =
5934 (zcb->zcb_totalasize - bytes) / 1024 / kb_per_sec;
5936 /* make sure nicenum has enough space */
5937 _Static_assert(sizeof (buf) >= NN_NUMBUF_SZ, "buf truncated");
5939 zfs_nicebytes(bytes, buf, sizeof (buf));
5940 (void) fprintf(stderr,
5941 "\r%5s completed (%4"PRIu64"MB/s) "
5942 "estimated time remaining: "
5943 "%"PRIu64"hr %02"PRIu64"min %02"PRIu64"sec ",
5944 buf, kb_per_sec / 1024,
5945 sec_remaining / 60 / 60,
5946 sec_remaining / 60 % 60,
5947 sec_remaining % 60);
5949 zcb->zcb_lastprint = now;
5952 return (0);
5955 static void
5956 zdb_leak(void *arg, uint64_t start, uint64_t size)
5958 vdev_t *vd = arg;
5960 (void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
5961 (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
5964 static metaslab_ops_t zdb_metaslab_ops = {
5965 NULL /* alloc */
5968 static int
5969 load_unflushed_svr_segs_cb(spa_t *spa, space_map_entry_t *sme,
5970 uint64_t txg, void *arg)
5972 spa_vdev_removal_t *svr = arg;
5974 uint64_t offset = sme->sme_offset;
5975 uint64_t size = sme->sme_run;
5977 /* skip vdevs we don't care about */
5978 if (sme->sme_vdev != svr->svr_vdev_id)
5979 return (0);
5981 vdev_t *vd = vdev_lookup_top(spa, sme->sme_vdev);
5982 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5983 ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
5985 if (txg < metaslab_unflushed_txg(ms))
5986 return (0);
5988 if (sme->sme_type == SM_ALLOC)
5989 range_tree_add(svr->svr_allocd_segs, offset, size);
5990 else
5991 range_tree_remove(svr->svr_allocd_segs, offset, size);
5993 return (0);
5996 static void
5997 claim_segment_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5998 uint64_t size, void *arg)
6000 (void) inner_offset, (void) arg;
6003 * This callback was called through a remap from
6004 * a device being removed. Therefore, the vdev that
6005 * this callback is applied to is a concrete
6006 * vdev.
6008 ASSERT(vdev_is_concrete(vd));
6010 VERIFY0(metaslab_claim_impl(vd, offset, size,
6011 spa_min_claim_txg(vd->vdev_spa)));
6014 static void
6015 claim_segment_cb(void *arg, uint64_t offset, uint64_t size)
6017 vdev_t *vd = arg;
6019 vdev_indirect_ops.vdev_op_remap(vd, offset, size,
6020 claim_segment_impl_cb, NULL);
6024 * After accounting for all allocated blocks that are directly referenced,
6025 * we might have missed a reference to a block from a partially complete
6026 * (and thus unused) indirect mapping object. We perform a secondary pass
6027 * through the metaslabs we have already mapped and claim the destination
6028 * blocks.
6030 static void
6031 zdb_claim_removing(spa_t *spa, zdb_cb_t *zcb)
6033 if (dump_opt['L'])
6034 return;
6036 if (spa->spa_vdev_removal == NULL)
6037 return;
6039 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6041 spa_vdev_removal_t *svr = spa->spa_vdev_removal;
6042 vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
6043 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6045 ASSERT0(range_tree_space(svr->svr_allocd_segs));
6047 range_tree_t *allocs = range_tree_create(NULL, RANGE_SEG64, NULL, 0, 0);
6048 for (uint64_t msi = 0; msi < vd->vdev_ms_count; msi++) {
6049 metaslab_t *msp = vd->vdev_ms[msi];
6051 ASSERT0(range_tree_space(allocs));
6052 if (msp->ms_sm != NULL)
6053 VERIFY0(space_map_load(msp->ms_sm, allocs, SM_ALLOC));
6054 range_tree_vacate(allocs, range_tree_add, svr->svr_allocd_segs);
6056 range_tree_destroy(allocs);
6058 iterate_through_spacemap_logs(spa, load_unflushed_svr_segs_cb, svr);
6061 * Clear everything past what has been synced,
6062 * because we have not allocated mappings for
6063 * it yet.
6065 range_tree_clear(svr->svr_allocd_segs,
6066 vdev_indirect_mapping_max_offset(vim),
6067 vd->vdev_asize - vdev_indirect_mapping_max_offset(vim));
6069 zcb->zcb_removing_size += range_tree_space(svr->svr_allocd_segs);
6070 range_tree_vacate(svr->svr_allocd_segs, claim_segment_cb, vd);
6072 spa_config_exit(spa, SCL_CONFIG, FTAG);
6075 static int
6076 increment_indirect_mapping_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
6077 dmu_tx_t *tx)
6079 (void) tx;
6080 zdb_cb_t *zcb = arg;
6081 spa_t *spa = zcb->zcb_spa;
6082 vdev_t *vd;
6083 const dva_t *dva = &bp->blk_dva[0];
6085 ASSERT(!bp_freed);
6086 ASSERT(!dump_opt['L']);
6087 ASSERT3U(BP_GET_NDVAS(bp), ==, 1);
6089 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
6090 vd = vdev_lookup_top(zcb->zcb_spa, DVA_GET_VDEV(dva));
6091 ASSERT3P(vd, !=, NULL);
6092 spa_config_exit(spa, SCL_VDEV, FTAG);
6094 ASSERT(vd->vdev_indirect_config.vic_mapping_object != 0);
6095 ASSERT3P(zcb->zcb_vd_obsolete_counts[vd->vdev_id], !=, NULL);
6097 vdev_indirect_mapping_increment_obsolete_count(
6098 vd->vdev_indirect_mapping,
6099 DVA_GET_OFFSET(dva), DVA_GET_ASIZE(dva),
6100 zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
6102 return (0);
6105 static uint32_t *
6106 zdb_load_obsolete_counts(vdev_t *vd)
6108 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6109 spa_t *spa = vd->vdev_spa;
6110 spa_condensing_indirect_phys_t *scip =
6111 &spa->spa_condensing_indirect_phys;
6112 uint64_t obsolete_sm_object;
6113 uint32_t *counts;
6115 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
6116 EQUIV(obsolete_sm_object != 0, vd->vdev_obsolete_sm != NULL);
6117 counts = vdev_indirect_mapping_load_obsolete_counts(vim);
6118 if (vd->vdev_obsolete_sm != NULL) {
6119 vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
6120 vd->vdev_obsolete_sm);
6122 if (scip->scip_vdev == vd->vdev_id &&
6123 scip->scip_prev_obsolete_sm_object != 0) {
6124 space_map_t *prev_obsolete_sm = NULL;
6125 VERIFY0(space_map_open(&prev_obsolete_sm, spa->spa_meta_objset,
6126 scip->scip_prev_obsolete_sm_object, 0, vd->vdev_asize, 0));
6127 vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
6128 prev_obsolete_sm);
6129 space_map_close(prev_obsolete_sm);
6131 return (counts);
6134 static void
6135 zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
6137 ddt_bookmark_t ddb = {0};
6138 ddt_entry_t dde;
6139 int error;
6140 int p;
6142 ASSERT(!dump_opt['L']);
6144 while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
6145 blkptr_t blk;
6146 ddt_phys_t *ddp = dde.dde_phys;
6148 if (ddb.ddb_class == DDT_CLASS_UNIQUE)
6149 return;
6151 ASSERT(ddt_phys_total_refcnt(&dde) > 1);
6153 for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
6154 if (ddp->ddp_phys_birth == 0)
6155 continue;
6156 ddt_bp_create(ddb.ddb_checksum,
6157 &dde.dde_key, ddp, &blk);
6158 if (p == DDT_PHYS_DITTO) {
6159 zdb_count_block(zcb, NULL, &blk, ZDB_OT_DITTO);
6160 } else {
6161 zcb->zcb_dedup_asize +=
6162 BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
6163 zcb->zcb_dedup_blocks++;
6166 ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
6167 ddt_enter(ddt);
6168 VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
6169 ddt_exit(ddt);
6172 ASSERT(error == ENOENT);
6175 typedef struct checkpoint_sm_exclude_entry_arg {
6176 vdev_t *cseea_vd;
6177 uint64_t cseea_checkpoint_size;
6178 } checkpoint_sm_exclude_entry_arg_t;
6180 static int
6181 checkpoint_sm_exclude_entry_cb(space_map_entry_t *sme, void *arg)
6183 checkpoint_sm_exclude_entry_arg_t *cseea = arg;
6184 vdev_t *vd = cseea->cseea_vd;
6185 metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
6186 uint64_t end = sme->sme_offset + sme->sme_run;
6188 ASSERT(sme->sme_type == SM_FREE);
6191 * Since the vdev_checkpoint_sm exists in the vdev level
6192 * and the ms_sm space maps exist in the metaslab level,
6193 * an entry in the checkpoint space map could theoretically
6194 * cross the boundaries of the metaslab that it belongs.
6196 * In reality, because of the way that we populate and
6197 * manipulate the checkpoint's space maps currently,
6198 * there shouldn't be any entries that cross metaslabs.
6199 * Hence the assertion below.
6201 * That said, there is no fundamental requirement that
6202 * the checkpoint's space map entries should not cross
6203 * metaslab boundaries. So if needed we could add code
6204 * that handles metaslab-crossing segments in the future.
6206 VERIFY3U(sme->sme_offset, >=, ms->ms_start);
6207 VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
6210 * By removing the entry from the allocated segments we
6211 * also verify that the entry is there to begin with.
6213 mutex_enter(&ms->ms_lock);
6214 range_tree_remove(ms->ms_allocatable, sme->sme_offset, sme->sme_run);
6215 mutex_exit(&ms->ms_lock);
6217 cseea->cseea_checkpoint_size += sme->sme_run;
6218 return (0);
6221 static void
6222 zdb_leak_init_vdev_exclude_checkpoint(vdev_t *vd, zdb_cb_t *zcb)
6224 spa_t *spa = vd->vdev_spa;
6225 space_map_t *checkpoint_sm = NULL;
6226 uint64_t checkpoint_sm_obj;
6229 * If there is no vdev_top_zap, we are in a pool whose
6230 * version predates the pool checkpoint feature.
6232 if (vd->vdev_top_zap == 0)
6233 return;
6236 * If there is no reference of the vdev_checkpoint_sm in
6237 * the vdev_top_zap, then one of the following scenarios
6238 * is true:
6240 * 1] There is no checkpoint
6241 * 2] There is a checkpoint, but no checkpointed blocks
6242 * have been freed yet
6243 * 3] The current vdev is indirect
6245 * In these cases we return immediately.
6247 if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
6248 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
6249 return;
6251 VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
6252 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1,
6253 &checkpoint_sm_obj));
6255 checkpoint_sm_exclude_entry_arg_t cseea;
6256 cseea.cseea_vd = vd;
6257 cseea.cseea_checkpoint_size = 0;
6259 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
6260 checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
6262 VERIFY0(space_map_iterate(checkpoint_sm,
6263 space_map_length(checkpoint_sm),
6264 checkpoint_sm_exclude_entry_cb, &cseea));
6265 space_map_close(checkpoint_sm);
6267 zcb->zcb_checkpoint_size += cseea.cseea_checkpoint_size;
6270 static void
6271 zdb_leak_init_exclude_checkpoint(spa_t *spa, zdb_cb_t *zcb)
6273 ASSERT(!dump_opt['L']);
6275 vdev_t *rvd = spa->spa_root_vdev;
6276 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
6277 ASSERT3U(c, ==, rvd->vdev_child[c]->vdev_id);
6278 zdb_leak_init_vdev_exclude_checkpoint(rvd->vdev_child[c], zcb);
6282 static int
6283 count_unflushed_space_cb(spa_t *spa, space_map_entry_t *sme,
6284 uint64_t txg, void *arg)
6286 int64_t *ualloc_space = arg;
6288 uint64_t offset = sme->sme_offset;
6289 uint64_t vdev_id = sme->sme_vdev;
6291 vdev_t *vd = vdev_lookup_top(spa, vdev_id);
6292 if (!vdev_is_concrete(vd))
6293 return (0);
6295 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
6296 ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
6298 if (txg < metaslab_unflushed_txg(ms))
6299 return (0);
6301 if (sme->sme_type == SM_ALLOC)
6302 *ualloc_space += sme->sme_run;
6303 else
6304 *ualloc_space -= sme->sme_run;
6306 return (0);
6309 static int64_t
6310 get_unflushed_alloc_space(spa_t *spa)
6312 if (dump_opt['L'])
6313 return (0);
6315 int64_t ualloc_space = 0;
6316 iterate_through_spacemap_logs(spa, count_unflushed_space_cb,
6317 &ualloc_space);
6318 return (ualloc_space);
6321 static int
6322 load_unflushed_cb(spa_t *spa, space_map_entry_t *sme, uint64_t txg, void *arg)
6324 maptype_t *uic_maptype = arg;
6326 uint64_t offset = sme->sme_offset;
6327 uint64_t size = sme->sme_run;
6328 uint64_t vdev_id = sme->sme_vdev;
6330 vdev_t *vd = vdev_lookup_top(spa, vdev_id);
6332 /* skip indirect vdevs */
6333 if (!vdev_is_concrete(vd))
6334 return (0);
6336 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
6338 ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
6339 ASSERT(*uic_maptype == SM_ALLOC || *uic_maptype == SM_FREE);
6341 if (txg < metaslab_unflushed_txg(ms))
6342 return (0);
6344 if (*uic_maptype == sme->sme_type)
6345 range_tree_add(ms->ms_allocatable, offset, size);
6346 else
6347 range_tree_remove(ms->ms_allocatable, offset, size);
6349 return (0);
6352 static void
6353 load_unflushed_to_ms_allocatables(spa_t *spa, maptype_t maptype)
6355 iterate_through_spacemap_logs(spa, load_unflushed_cb, &maptype);
6358 static void
6359 load_concrete_ms_allocatable_trees(spa_t *spa, maptype_t maptype)
6361 vdev_t *rvd = spa->spa_root_vdev;
6362 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
6363 vdev_t *vd = rvd->vdev_child[i];
6365 ASSERT3U(i, ==, vd->vdev_id);
6367 if (vd->vdev_ops == &vdev_indirect_ops)
6368 continue;
6370 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
6371 metaslab_t *msp = vd->vdev_ms[m];
6373 (void) fprintf(stderr,
6374 "\rloading concrete vdev %llu, "
6375 "metaslab %llu of %llu ...",
6376 (longlong_t)vd->vdev_id,
6377 (longlong_t)msp->ms_id,
6378 (longlong_t)vd->vdev_ms_count);
6380 mutex_enter(&msp->ms_lock);
6381 range_tree_vacate(msp->ms_allocatable, NULL, NULL);
6384 * We don't want to spend the CPU manipulating the
6385 * size-ordered tree, so clear the range_tree ops.
6387 msp->ms_allocatable->rt_ops = NULL;
6389 if (msp->ms_sm != NULL) {
6390 VERIFY0(space_map_load(msp->ms_sm,
6391 msp->ms_allocatable, maptype));
6393 if (!msp->ms_loaded)
6394 msp->ms_loaded = B_TRUE;
6395 mutex_exit(&msp->ms_lock);
6399 load_unflushed_to_ms_allocatables(spa, maptype);
6403 * vm_idxp is an in-out parameter which (for indirect vdevs) is the
6404 * index in vim_entries that has the first entry in this metaslab.
6405 * On return, it will be set to the first entry after this metaslab.
6407 static void
6408 load_indirect_ms_allocatable_tree(vdev_t *vd, metaslab_t *msp,
6409 uint64_t *vim_idxp)
6411 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6413 mutex_enter(&msp->ms_lock);
6414 range_tree_vacate(msp->ms_allocatable, NULL, NULL);
6417 * We don't want to spend the CPU manipulating the
6418 * size-ordered tree, so clear the range_tree ops.
6420 msp->ms_allocatable->rt_ops = NULL;
6422 for (; *vim_idxp < vdev_indirect_mapping_num_entries(vim);
6423 (*vim_idxp)++) {
6424 vdev_indirect_mapping_entry_phys_t *vimep =
6425 &vim->vim_entries[*vim_idxp];
6426 uint64_t ent_offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
6427 uint64_t ent_len = DVA_GET_ASIZE(&vimep->vimep_dst);
6428 ASSERT3U(ent_offset, >=, msp->ms_start);
6429 if (ent_offset >= msp->ms_start + msp->ms_size)
6430 break;
6433 * Mappings do not cross metaslab boundaries,
6434 * because we create them by walking the metaslabs.
6436 ASSERT3U(ent_offset + ent_len, <=,
6437 msp->ms_start + msp->ms_size);
6438 range_tree_add(msp->ms_allocatable, ent_offset, ent_len);
6441 if (!msp->ms_loaded)
6442 msp->ms_loaded = B_TRUE;
6443 mutex_exit(&msp->ms_lock);
6446 static void
6447 zdb_leak_init_prepare_indirect_vdevs(spa_t *spa, zdb_cb_t *zcb)
6449 ASSERT(!dump_opt['L']);
6451 vdev_t *rvd = spa->spa_root_vdev;
6452 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
6453 vdev_t *vd = rvd->vdev_child[c];
6455 ASSERT3U(c, ==, vd->vdev_id);
6457 if (vd->vdev_ops != &vdev_indirect_ops)
6458 continue;
6461 * Note: we don't check for mapping leaks on
6462 * removing vdevs because their ms_allocatable's
6463 * are used to look for leaks in allocated space.
6465 zcb->zcb_vd_obsolete_counts[c] = zdb_load_obsolete_counts(vd);
6468 * Normally, indirect vdevs don't have any
6469 * metaslabs. We want to set them up for
6470 * zio_claim().
6472 vdev_metaslab_group_create(vd);
6473 VERIFY0(vdev_metaslab_init(vd, 0));
6475 vdev_indirect_mapping_t *vim __maybe_unused =
6476 vd->vdev_indirect_mapping;
6477 uint64_t vim_idx = 0;
6478 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
6480 (void) fprintf(stderr,
6481 "\rloading indirect vdev %llu, "
6482 "metaslab %llu of %llu ...",
6483 (longlong_t)vd->vdev_id,
6484 (longlong_t)vd->vdev_ms[m]->ms_id,
6485 (longlong_t)vd->vdev_ms_count);
6487 load_indirect_ms_allocatable_tree(vd, vd->vdev_ms[m],
6488 &vim_idx);
6490 ASSERT3U(vim_idx, ==, vdev_indirect_mapping_num_entries(vim));
6494 static void
6495 zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
6497 zcb->zcb_spa = spa;
6499 if (dump_opt['L'])
6500 return;
6502 dsl_pool_t *dp = spa->spa_dsl_pool;
6503 vdev_t *rvd = spa->spa_root_vdev;
6506 * We are going to be changing the meaning of the metaslab's
6507 * ms_allocatable. Ensure that the allocator doesn't try to
6508 * use the tree.
6510 spa->spa_normal_class->mc_ops = &zdb_metaslab_ops;
6511 spa->spa_log_class->mc_ops = &zdb_metaslab_ops;
6512 spa->spa_embedded_log_class->mc_ops = &zdb_metaslab_ops;
6514 zcb->zcb_vd_obsolete_counts =
6515 umem_zalloc(rvd->vdev_children * sizeof (uint32_t *),
6516 UMEM_NOFAIL);
6519 * For leak detection, we overload the ms_allocatable trees
6520 * to contain allocated segments instead of free segments.
6521 * As a result, we can't use the normal metaslab_load/unload
6522 * interfaces.
6524 zdb_leak_init_prepare_indirect_vdevs(spa, zcb);
6525 load_concrete_ms_allocatable_trees(spa, SM_ALLOC);
6528 * On load_concrete_ms_allocatable_trees() we loaded all the
6529 * allocated entries from the ms_sm to the ms_allocatable for
6530 * each metaslab. If the pool has a checkpoint or is in the
6531 * middle of discarding a checkpoint, some of these blocks
6532 * may have been freed but their ms_sm may not have been
6533 * updated because they are referenced by the checkpoint. In
6534 * order to avoid false-positives during leak-detection, we
6535 * go through the vdev's checkpoint space map and exclude all
6536 * its entries from their relevant ms_allocatable.
6538 * We also aggregate the space held by the checkpoint and add
6539 * it to zcb_checkpoint_size.
6541 * Note that at this point we are also verifying that all the
6542 * entries on the checkpoint_sm are marked as allocated in
6543 * the ms_sm of their relevant metaslab.
6544 * [see comment in checkpoint_sm_exclude_entry_cb()]
6546 zdb_leak_init_exclude_checkpoint(spa, zcb);
6547 ASSERT3U(zcb->zcb_checkpoint_size, ==, spa_get_checkpoint_space(spa));
6549 /* for cleaner progress output */
6550 (void) fprintf(stderr, "\n");
6552 if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
6553 ASSERT(spa_feature_is_enabled(spa,
6554 SPA_FEATURE_DEVICE_REMOVAL));
6555 (void) bpobj_iterate_nofree(&dp->dp_obsolete_bpobj,
6556 increment_indirect_mapping_cb, zcb, NULL);
6559 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6560 zdb_ddt_leak_init(spa, zcb);
6561 spa_config_exit(spa, SCL_CONFIG, FTAG);
6564 static boolean_t
6565 zdb_check_for_obsolete_leaks(vdev_t *vd, zdb_cb_t *zcb)
6567 boolean_t leaks = B_FALSE;
6568 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6569 uint64_t total_leaked = 0;
6570 boolean_t are_precise = B_FALSE;
6572 ASSERT(vim != NULL);
6574 for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
6575 vdev_indirect_mapping_entry_phys_t *vimep =
6576 &vim->vim_entries[i];
6577 uint64_t obsolete_bytes = 0;
6578 uint64_t offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
6579 metaslab_t *msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
6582 * This is not very efficient but it's easy to
6583 * verify correctness.
6585 for (uint64_t inner_offset = 0;
6586 inner_offset < DVA_GET_ASIZE(&vimep->vimep_dst);
6587 inner_offset += 1ULL << vd->vdev_ashift) {
6588 if (range_tree_contains(msp->ms_allocatable,
6589 offset + inner_offset, 1ULL << vd->vdev_ashift)) {
6590 obsolete_bytes += 1ULL << vd->vdev_ashift;
6594 int64_t bytes_leaked = obsolete_bytes -
6595 zcb->zcb_vd_obsolete_counts[vd->vdev_id][i];
6596 ASSERT3U(DVA_GET_ASIZE(&vimep->vimep_dst), >=,
6597 zcb->zcb_vd_obsolete_counts[vd->vdev_id][i]);
6599 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
6600 if (bytes_leaked != 0 && (are_precise || dump_opt['d'] >= 5)) {
6601 (void) printf("obsolete indirect mapping count "
6602 "mismatch on %llu:%llx:%llx : %llx bytes leaked\n",
6603 (u_longlong_t)vd->vdev_id,
6604 (u_longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
6605 (u_longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
6606 (u_longlong_t)bytes_leaked);
6608 total_leaked += ABS(bytes_leaked);
6611 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
6612 if (!are_precise && total_leaked > 0) {
6613 int pct_leaked = total_leaked * 100 /
6614 vdev_indirect_mapping_bytes_mapped(vim);
6615 (void) printf("cannot verify obsolete indirect mapping "
6616 "counts of vdev %llu because precise feature was not "
6617 "enabled when it was removed: %d%% (%llx bytes) of mapping"
6618 "unreferenced\n",
6619 (u_longlong_t)vd->vdev_id, pct_leaked,
6620 (u_longlong_t)total_leaked);
6621 } else if (total_leaked > 0) {
6622 (void) printf("obsolete indirect mapping count mismatch "
6623 "for vdev %llu -- %llx total bytes mismatched\n",
6624 (u_longlong_t)vd->vdev_id,
6625 (u_longlong_t)total_leaked);
6626 leaks |= B_TRUE;
6629 vdev_indirect_mapping_free_obsolete_counts(vim,
6630 zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
6631 zcb->zcb_vd_obsolete_counts[vd->vdev_id] = NULL;
6633 return (leaks);
6636 static boolean_t
6637 zdb_leak_fini(spa_t *spa, zdb_cb_t *zcb)
6639 if (dump_opt['L'])
6640 return (B_FALSE);
6642 boolean_t leaks = B_FALSE;
6643 vdev_t *rvd = spa->spa_root_vdev;
6644 for (unsigned c = 0; c < rvd->vdev_children; c++) {
6645 vdev_t *vd = rvd->vdev_child[c];
6647 if (zcb->zcb_vd_obsolete_counts[c] != NULL) {
6648 leaks |= zdb_check_for_obsolete_leaks(vd, zcb);
6651 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
6652 metaslab_t *msp = vd->vdev_ms[m];
6653 ASSERT3P(msp->ms_group, ==, (msp->ms_group->mg_class ==
6654 spa_embedded_log_class(spa)) ?
6655 vd->vdev_log_mg : vd->vdev_mg);
6658 * ms_allocatable has been overloaded
6659 * to contain allocated segments. Now that
6660 * we finished traversing all blocks, any
6661 * block that remains in the ms_allocatable
6662 * represents an allocated block that we
6663 * did not claim during the traversal.
6664 * Claimed blocks would have been removed
6665 * from the ms_allocatable. For indirect
6666 * vdevs, space remaining in the tree
6667 * represents parts of the mapping that are
6668 * not referenced, which is not a bug.
6670 if (vd->vdev_ops == &vdev_indirect_ops) {
6671 range_tree_vacate(msp->ms_allocatable,
6672 NULL, NULL);
6673 } else {
6674 range_tree_vacate(msp->ms_allocatable,
6675 zdb_leak, vd);
6677 if (msp->ms_loaded) {
6678 msp->ms_loaded = B_FALSE;
6683 umem_free(zcb->zcb_vd_obsolete_counts,
6684 rvd->vdev_children * sizeof (uint32_t *));
6685 zcb->zcb_vd_obsolete_counts = NULL;
6687 return (leaks);
6690 static int
6691 count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
6693 (void) tx;
6694 zdb_cb_t *zcb = arg;
6696 if (dump_opt['b'] >= 5) {
6697 char blkbuf[BP_SPRINTF_LEN];
6698 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
6699 (void) printf("[%s] %s\n",
6700 "deferred free", blkbuf);
6702 zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
6703 return (0);
6707 * Iterate over livelists which have been destroyed by the user but
6708 * are still present in the MOS, waiting to be freed
6710 static void
6711 iterate_deleted_livelists(spa_t *spa, ll_iter_t func, void *arg)
6713 objset_t *mos = spa->spa_meta_objset;
6714 uint64_t zap_obj;
6715 int err = zap_lookup(mos, DMU_POOL_DIRECTORY_OBJECT,
6716 DMU_POOL_DELETED_CLONES, sizeof (uint64_t), 1, &zap_obj);
6717 if (err == ENOENT)
6718 return;
6719 ASSERT0(err);
6721 zap_cursor_t zc;
6722 zap_attribute_t attr;
6723 dsl_deadlist_t ll;
6724 /* NULL out os prior to dsl_deadlist_open in case it's garbage */
6725 ll.dl_os = NULL;
6726 for (zap_cursor_init(&zc, mos, zap_obj);
6727 zap_cursor_retrieve(&zc, &attr) == 0;
6728 (void) zap_cursor_advance(&zc)) {
6729 dsl_deadlist_open(&ll, mos, attr.za_first_integer);
6730 func(&ll, arg);
6731 dsl_deadlist_close(&ll);
6733 zap_cursor_fini(&zc);
6736 static int
6737 bpobj_count_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
6738 dmu_tx_t *tx)
6740 ASSERT(!bp_freed);
6741 return (count_block_cb(arg, bp, tx));
6744 static int
6745 livelist_entry_count_blocks_cb(void *args, dsl_deadlist_entry_t *dle)
6747 zdb_cb_t *zbc = args;
6748 bplist_t blks;
6749 bplist_create(&blks);
6750 /* determine which blocks have been alloc'd but not freed */
6751 VERIFY0(dsl_process_sub_livelist(&dle->dle_bpobj, &blks, NULL, NULL));
6752 /* count those blocks */
6753 (void) bplist_iterate(&blks, count_block_cb, zbc, NULL);
6754 bplist_destroy(&blks);
6755 return (0);
6758 static void
6759 livelist_count_blocks(dsl_deadlist_t *ll, void *arg)
6761 dsl_deadlist_iterate(ll, livelist_entry_count_blocks_cb, arg);
6765 * Count the blocks in the livelists that have been destroyed by the user
6766 * but haven't yet been freed.
6768 static void
6769 deleted_livelists_count_blocks(spa_t *spa, zdb_cb_t *zbc)
6771 iterate_deleted_livelists(spa, livelist_count_blocks, zbc);
6774 static void
6775 dump_livelist_cb(dsl_deadlist_t *ll, void *arg)
6777 ASSERT3P(arg, ==, NULL);
6778 global_feature_count[SPA_FEATURE_LIVELIST]++;
6779 dump_blkptr_list(ll, "Deleted Livelist");
6780 dsl_deadlist_iterate(ll, sublivelist_verify_lightweight, NULL);
6784 * Print out, register object references to, and increment feature counts for
6785 * livelists that have been destroyed by the user but haven't yet been freed.
6787 static void
6788 deleted_livelists_dump_mos(spa_t *spa)
6790 uint64_t zap_obj;
6791 objset_t *mos = spa->spa_meta_objset;
6792 int err = zap_lookup(mos, DMU_POOL_DIRECTORY_OBJECT,
6793 DMU_POOL_DELETED_CLONES, sizeof (uint64_t), 1, &zap_obj);
6794 if (err == ENOENT)
6795 return;
6796 mos_obj_refd(zap_obj);
6797 iterate_deleted_livelists(spa, dump_livelist_cb, NULL);
6800 static int
6801 zdb_brt_entry_compare(const void *zcn1, const void *zcn2)
6803 const dva_t *dva1 = &((const zdb_brt_entry_t *)zcn1)->zbre_dva;
6804 const dva_t *dva2 = &((const zdb_brt_entry_t *)zcn2)->zbre_dva;
6805 int cmp;
6807 cmp = TREE_CMP(DVA_GET_VDEV(dva1), DVA_GET_VDEV(dva2));
6808 if (cmp == 0)
6809 cmp = TREE_CMP(DVA_GET_OFFSET(dva1), DVA_GET_OFFSET(dva2));
6811 return (cmp);
6814 static int
6815 dump_block_stats(spa_t *spa)
6817 zdb_cb_t *zcb;
6818 zdb_blkstats_t *zb, *tzb;
6819 uint64_t norm_alloc, norm_space, total_alloc, total_found;
6820 int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
6821 TRAVERSE_NO_DECRYPT | TRAVERSE_HARD;
6822 boolean_t leaks = B_FALSE;
6823 int e, c, err;
6824 bp_embedded_type_t i;
6826 zcb = umem_zalloc(sizeof (zdb_cb_t), UMEM_NOFAIL);
6828 if (spa_feature_is_active(spa, SPA_FEATURE_BLOCK_CLONING)) {
6829 avl_create(&zcb->zcb_brt, zdb_brt_entry_compare,
6830 sizeof (zdb_brt_entry_t),
6831 offsetof(zdb_brt_entry_t, zbre_node));
6832 zcb->zcb_brt_is_active = B_TRUE;
6835 (void) printf("\nTraversing all blocks %s%s%s%s%s...\n\n",
6836 (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
6837 (dump_opt['c'] == 1) ? "metadata " : "",
6838 dump_opt['c'] ? "checksums " : "",
6839 (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
6840 !dump_opt['L'] ? "nothing leaked " : "");
6843 * When leak detection is enabled we load all space maps as SM_ALLOC
6844 * maps, then traverse the pool claiming each block we discover. If
6845 * the pool is perfectly consistent, the segment trees will be empty
6846 * when we're done. Anything left over is a leak; any block we can't
6847 * claim (because it's not part of any space map) is a double
6848 * allocation, reference to a freed block, or an unclaimed log block.
6850 * When leak detection is disabled (-L option) we still traverse the
6851 * pool claiming each block we discover, but we skip opening any space
6852 * maps.
6854 zdb_leak_init(spa, zcb);
6857 * If there's a deferred-free bplist, process that first.
6859 (void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
6860 bpobj_count_block_cb, zcb, NULL);
6862 if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
6863 (void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
6864 bpobj_count_block_cb, zcb, NULL);
6867 zdb_claim_removing(spa, zcb);
6869 if (spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
6870 VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
6871 spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
6872 zcb, NULL));
6875 deleted_livelists_count_blocks(spa, zcb);
6877 if (dump_opt['c'] > 1)
6878 flags |= TRAVERSE_PREFETCH_DATA;
6880 zcb->zcb_totalasize = metaslab_class_get_alloc(spa_normal_class(spa));
6881 zcb->zcb_totalasize += metaslab_class_get_alloc(spa_special_class(spa));
6882 zcb->zcb_totalasize += metaslab_class_get_alloc(spa_dedup_class(spa));
6883 zcb->zcb_totalasize +=
6884 metaslab_class_get_alloc(spa_embedded_log_class(spa));
6885 zcb->zcb_start = zcb->zcb_lastprint = gethrtime();
6886 err = traverse_pool(spa, 0, flags, zdb_blkptr_cb, zcb);
6889 * If we've traversed the data blocks then we need to wait for those
6890 * I/Os to complete. We leverage "The Godfather" zio to wait on
6891 * all async I/Os to complete.
6893 if (dump_opt['c']) {
6894 for (c = 0; c < max_ncpus; c++) {
6895 (void) zio_wait(spa->spa_async_zio_root[c]);
6896 spa->spa_async_zio_root[c] = zio_root(spa, NULL, NULL,
6897 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
6898 ZIO_FLAG_GODFATHER);
6901 ASSERT0(spa->spa_load_verify_bytes);
6904 * Done after zio_wait() since zcb_haderrors is modified in
6905 * zdb_blkptr_done()
6907 zcb->zcb_haderrors |= err;
6909 if (zcb->zcb_haderrors) {
6910 (void) printf("\nError counts:\n\n");
6911 (void) printf("\t%5s %s\n", "errno", "count");
6912 for (e = 0; e < 256; e++) {
6913 if (zcb->zcb_errors[e] != 0) {
6914 (void) printf("\t%5d %llu\n",
6915 e, (u_longlong_t)zcb->zcb_errors[e]);
6921 * Report any leaked segments.
6923 leaks |= zdb_leak_fini(spa, zcb);
6925 tzb = &zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
6927 norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
6928 norm_space = metaslab_class_get_space(spa_normal_class(spa));
6930 total_alloc = norm_alloc +
6931 metaslab_class_get_alloc(spa_log_class(spa)) +
6932 metaslab_class_get_alloc(spa_embedded_log_class(spa)) +
6933 metaslab_class_get_alloc(spa_special_class(spa)) +
6934 metaslab_class_get_alloc(spa_dedup_class(spa)) +
6935 get_unflushed_alloc_space(spa);
6936 total_found =
6937 tzb->zb_asize - zcb->zcb_dedup_asize - zcb->zcb_clone_asize +
6938 zcb->zcb_removing_size + zcb->zcb_checkpoint_size;
6940 if (total_found == total_alloc && !dump_opt['L']) {
6941 (void) printf("\n\tNo leaks (block sum matches space"
6942 " maps exactly)\n");
6943 } else if (!dump_opt['L']) {
6944 (void) printf("block traversal size %llu != alloc %llu "
6945 "(%s %lld)\n",
6946 (u_longlong_t)total_found,
6947 (u_longlong_t)total_alloc,
6948 (dump_opt['L']) ? "unreachable" : "leaked",
6949 (longlong_t)(total_alloc - total_found));
6950 leaks = B_TRUE;
6953 if (tzb->zb_count == 0) {
6954 umem_free(zcb, sizeof (zdb_cb_t));
6955 return (2);
6958 (void) printf("\n");
6959 (void) printf("\t%-16s %14llu\n", "bp count:",
6960 (u_longlong_t)tzb->zb_count);
6961 (void) printf("\t%-16s %14llu\n", "ganged count:",
6962 (longlong_t)tzb->zb_gangs);
6963 (void) printf("\t%-16s %14llu avg: %6llu\n", "bp logical:",
6964 (u_longlong_t)tzb->zb_lsize,
6965 (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
6966 (void) printf("\t%-16s %14llu avg: %6llu compression: %6.2f\n",
6967 "bp physical:", (u_longlong_t)tzb->zb_psize,
6968 (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
6969 (double)tzb->zb_lsize / tzb->zb_psize);
6970 (void) printf("\t%-16s %14llu avg: %6llu compression: %6.2f\n",
6971 "bp allocated:", (u_longlong_t)tzb->zb_asize,
6972 (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
6973 (double)tzb->zb_lsize / tzb->zb_asize);
6974 (void) printf("\t%-16s %14llu ref>1: %6llu deduplication: %6.2f\n",
6975 "bp deduped:", (u_longlong_t)zcb->zcb_dedup_asize,
6976 (u_longlong_t)zcb->zcb_dedup_blocks,
6977 (double)zcb->zcb_dedup_asize / tzb->zb_asize + 1.0);
6978 (void) printf("\t%-16s %14llu count: %6llu\n",
6979 "bp cloned:", (u_longlong_t)zcb->zcb_clone_asize,
6980 (u_longlong_t)zcb->zcb_clone_blocks);
6981 (void) printf("\t%-16s %14llu used: %5.2f%%\n", "Normal class:",
6982 (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
6984 if (spa_special_class(spa)->mc_allocator[0].mca_rotor != NULL) {
6985 uint64_t alloc = metaslab_class_get_alloc(
6986 spa_special_class(spa));
6987 uint64_t space = metaslab_class_get_space(
6988 spa_special_class(spa));
6990 (void) printf("\t%-16s %14llu used: %5.2f%%\n",
6991 "Special class", (u_longlong_t)alloc,
6992 100.0 * alloc / space);
6995 if (spa_dedup_class(spa)->mc_allocator[0].mca_rotor != NULL) {
6996 uint64_t alloc = metaslab_class_get_alloc(
6997 spa_dedup_class(spa));
6998 uint64_t space = metaslab_class_get_space(
6999 spa_dedup_class(spa));
7001 (void) printf("\t%-16s %14llu used: %5.2f%%\n",
7002 "Dedup class", (u_longlong_t)alloc,
7003 100.0 * alloc / space);
7006 if (spa_embedded_log_class(spa)->mc_allocator[0].mca_rotor != NULL) {
7007 uint64_t alloc = metaslab_class_get_alloc(
7008 spa_embedded_log_class(spa));
7009 uint64_t space = metaslab_class_get_space(
7010 spa_embedded_log_class(spa));
7012 (void) printf("\t%-16s %14llu used: %5.2f%%\n",
7013 "Embedded log class", (u_longlong_t)alloc,
7014 100.0 * alloc / space);
7017 for (i = 0; i < NUM_BP_EMBEDDED_TYPES; i++) {
7018 if (zcb->zcb_embedded_blocks[i] == 0)
7019 continue;
7020 (void) printf("\n");
7021 (void) printf("\tadditional, non-pointer bps of type %u: "
7022 "%10llu\n",
7023 i, (u_longlong_t)zcb->zcb_embedded_blocks[i]);
7025 if (dump_opt['b'] >= 3) {
7026 (void) printf("\t number of (compressed) bytes: "
7027 "number of bps\n");
7028 dump_histogram(zcb->zcb_embedded_histogram[i],
7029 sizeof (zcb->zcb_embedded_histogram[i]) /
7030 sizeof (zcb->zcb_embedded_histogram[i][0]), 0);
7034 if (tzb->zb_ditto_samevdev != 0) {
7035 (void) printf("\tDittoed blocks on same vdev: %llu\n",
7036 (longlong_t)tzb->zb_ditto_samevdev);
7038 if (tzb->zb_ditto_same_ms != 0) {
7039 (void) printf("\tDittoed blocks in same metaslab: %llu\n",
7040 (longlong_t)tzb->zb_ditto_same_ms);
7043 for (uint64_t v = 0; v < spa->spa_root_vdev->vdev_children; v++) {
7044 vdev_t *vd = spa->spa_root_vdev->vdev_child[v];
7045 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
7047 if (vim == NULL) {
7048 continue;
7051 char mem[32];
7052 zdb_nicenum(vdev_indirect_mapping_num_entries(vim),
7053 mem, vdev_indirect_mapping_size(vim));
7055 (void) printf("\tindirect vdev id %llu has %llu segments "
7056 "(%s in memory)\n",
7057 (longlong_t)vd->vdev_id,
7058 (longlong_t)vdev_indirect_mapping_num_entries(vim), mem);
7061 if (dump_opt['b'] >= 2) {
7062 int l, t, level;
7063 char csize[32], lsize[32], psize[32], asize[32];
7064 char avg[32], gang[32];
7065 (void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
7066 "\t avg\t comp\t%%Total\tType\n");
7068 zfs_blkstat_t *mdstats = umem_zalloc(sizeof (zfs_blkstat_t),
7069 UMEM_NOFAIL);
7071 for (t = 0; t <= ZDB_OT_TOTAL; t++) {
7072 const char *typename;
7074 /* make sure nicenum has enough space */
7075 _Static_assert(sizeof (csize) >= NN_NUMBUF_SZ,
7076 "csize truncated");
7077 _Static_assert(sizeof (lsize) >= NN_NUMBUF_SZ,
7078 "lsize truncated");
7079 _Static_assert(sizeof (psize) >= NN_NUMBUF_SZ,
7080 "psize truncated");
7081 _Static_assert(sizeof (asize) >= NN_NUMBUF_SZ,
7082 "asize truncated");
7083 _Static_assert(sizeof (avg) >= NN_NUMBUF_SZ,
7084 "avg truncated");
7085 _Static_assert(sizeof (gang) >= NN_NUMBUF_SZ,
7086 "gang truncated");
7088 if (t < DMU_OT_NUMTYPES)
7089 typename = dmu_ot[t].ot_name;
7090 else
7091 typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
7093 if (zcb->zcb_type[ZB_TOTAL][t].zb_asize == 0) {
7094 (void) printf("%6s\t%5s\t%5s\t%5s"
7095 "\t%5s\t%5s\t%6s\t%s\n",
7096 "-",
7097 "-",
7098 "-",
7099 "-",
7100 "-",
7101 "-",
7102 "-",
7103 typename);
7104 continue;
7107 for (l = ZB_TOTAL - 1; l >= -1; l--) {
7108 level = (l == -1 ? ZB_TOTAL : l);
7109 zb = &zcb->zcb_type[level][t];
7111 if (zb->zb_asize == 0)
7112 continue;
7114 if (level != ZB_TOTAL && t < DMU_OT_NUMTYPES &&
7115 (level > 0 || DMU_OT_IS_METADATA(t))) {
7116 mdstats->zb_count += zb->zb_count;
7117 mdstats->zb_lsize += zb->zb_lsize;
7118 mdstats->zb_psize += zb->zb_psize;
7119 mdstats->zb_asize += zb->zb_asize;
7120 mdstats->zb_gangs += zb->zb_gangs;
7123 if (dump_opt['b'] < 3 && level != ZB_TOTAL)
7124 continue;
7126 if (level == 0 && zb->zb_asize ==
7127 zcb->zcb_type[ZB_TOTAL][t].zb_asize)
7128 continue;
7130 zdb_nicenum(zb->zb_count, csize,
7131 sizeof (csize));
7132 zdb_nicenum(zb->zb_lsize, lsize,
7133 sizeof (lsize));
7134 zdb_nicenum(zb->zb_psize, psize,
7135 sizeof (psize));
7136 zdb_nicenum(zb->zb_asize, asize,
7137 sizeof (asize));
7138 zdb_nicenum(zb->zb_asize / zb->zb_count, avg,
7139 sizeof (avg));
7140 zdb_nicenum(zb->zb_gangs, gang, sizeof (gang));
7142 (void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
7143 "\t%5.2f\t%6.2f\t",
7144 csize, lsize, psize, asize, avg,
7145 (double)zb->zb_lsize / zb->zb_psize,
7146 100.0 * zb->zb_asize / tzb->zb_asize);
7148 if (level == ZB_TOTAL)
7149 (void) printf("%s\n", typename);
7150 else
7151 (void) printf(" L%d %s\n",
7152 level, typename);
7154 if (dump_opt['b'] >= 3 && zb->zb_gangs > 0) {
7155 (void) printf("\t number of ganged "
7156 "blocks: %s\n", gang);
7159 if (dump_opt['b'] >= 4) {
7160 (void) printf("psize "
7161 "(in 512-byte sectors): "
7162 "number of blocks\n");
7163 dump_histogram(zb->zb_psize_histogram,
7164 PSIZE_HISTO_SIZE, 0);
7168 zdb_nicenum(mdstats->zb_count, csize,
7169 sizeof (csize));
7170 zdb_nicenum(mdstats->zb_lsize, lsize,
7171 sizeof (lsize));
7172 zdb_nicenum(mdstats->zb_psize, psize,
7173 sizeof (psize));
7174 zdb_nicenum(mdstats->zb_asize, asize,
7175 sizeof (asize));
7176 zdb_nicenum(mdstats->zb_asize / mdstats->zb_count, avg,
7177 sizeof (avg));
7178 zdb_nicenum(mdstats->zb_gangs, gang, sizeof (gang));
7180 (void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
7181 "\t%5.2f\t%6.2f\t",
7182 csize, lsize, psize, asize, avg,
7183 (double)mdstats->zb_lsize / mdstats->zb_psize,
7184 100.0 * mdstats->zb_asize / tzb->zb_asize);
7185 (void) printf("%s\n", "Metadata Total");
7187 /* Output a table summarizing block sizes in the pool */
7188 if (dump_opt['b'] >= 2) {
7189 dump_size_histograms(zcb);
7192 umem_free(mdstats, sizeof (zfs_blkstat_t));
7195 (void) printf("\n");
7197 if (leaks) {
7198 umem_free(zcb, sizeof (zdb_cb_t));
7199 return (2);
7202 if (zcb->zcb_haderrors) {
7203 umem_free(zcb, sizeof (zdb_cb_t));
7204 return (3);
7207 umem_free(zcb, sizeof (zdb_cb_t));
7208 return (0);
7211 typedef struct zdb_ddt_entry {
7212 ddt_key_t zdde_key;
7213 uint64_t zdde_ref_blocks;
7214 uint64_t zdde_ref_lsize;
7215 uint64_t zdde_ref_psize;
7216 uint64_t zdde_ref_dsize;
7217 avl_node_t zdde_node;
7218 } zdb_ddt_entry_t;
7220 static int
7221 zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
7222 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
7224 (void) zilog, (void) dnp;
7225 avl_tree_t *t = arg;
7226 avl_index_t where;
7227 zdb_ddt_entry_t *zdde, zdde_search;
7229 if (zb->zb_level == ZB_DNODE_LEVEL || BP_IS_HOLE(bp) ||
7230 BP_IS_EMBEDDED(bp))
7231 return (0);
7233 if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
7234 (void) printf("traversing objset %llu, %llu objects, "
7235 "%lu blocks so far\n",
7236 (u_longlong_t)zb->zb_objset,
7237 (u_longlong_t)BP_GET_FILL(bp),
7238 avl_numnodes(t));
7241 if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
7242 BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
7243 return (0);
7245 ddt_key_fill(&zdde_search.zdde_key, bp);
7247 zdde = avl_find(t, &zdde_search, &where);
7249 if (zdde == NULL) {
7250 zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
7251 zdde->zdde_key = zdde_search.zdde_key;
7252 avl_insert(t, zdde, where);
7255 zdde->zdde_ref_blocks += 1;
7256 zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
7257 zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
7258 zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
7260 return (0);
7263 static void
7264 dump_simulated_ddt(spa_t *spa)
7266 avl_tree_t t;
7267 void *cookie = NULL;
7268 zdb_ddt_entry_t *zdde;
7269 ddt_histogram_t ddh_total = {{{0}}};
7270 ddt_stat_t dds_total = {0};
7272 avl_create(&t, ddt_entry_compare,
7273 sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
7275 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7277 (void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
7278 TRAVERSE_NO_DECRYPT, zdb_ddt_add_cb, &t);
7280 spa_config_exit(spa, SCL_CONFIG, FTAG);
7282 while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
7283 ddt_stat_t dds;
7284 uint64_t refcnt = zdde->zdde_ref_blocks;
7285 ASSERT(refcnt != 0);
7287 dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
7288 dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
7289 dds.dds_psize = zdde->zdde_ref_psize / refcnt;
7290 dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
7292 dds.dds_ref_blocks = zdde->zdde_ref_blocks;
7293 dds.dds_ref_lsize = zdde->zdde_ref_lsize;
7294 dds.dds_ref_psize = zdde->zdde_ref_psize;
7295 dds.dds_ref_dsize = zdde->zdde_ref_dsize;
7297 ddt_stat_add(&ddh_total.ddh_stat[highbit64(refcnt) - 1],
7298 &dds, 0);
7300 umem_free(zdde, sizeof (*zdde));
7303 avl_destroy(&t);
7305 ddt_histogram_stat(&dds_total, &ddh_total);
7307 (void) printf("Simulated DDT histogram:\n");
7309 zpool_dump_ddt(&dds_total, &ddh_total);
7311 dump_dedup_ratio(&dds_total);
7314 static int
7315 verify_device_removal_feature_counts(spa_t *spa)
7317 uint64_t dr_feature_refcount = 0;
7318 uint64_t oc_feature_refcount = 0;
7319 uint64_t indirect_vdev_count = 0;
7320 uint64_t precise_vdev_count = 0;
7321 uint64_t obsolete_counts_object_count = 0;
7322 uint64_t obsolete_sm_count = 0;
7323 uint64_t obsolete_counts_count = 0;
7324 uint64_t scip_count = 0;
7325 uint64_t obsolete_bpobj_count = 0;
7326 int ret = 0;
7328 spa_condensing_indirect_phys_t *scip =
7329 &spa->spa_condensing_indirect_phys;
7330 if (scip->scip_next_mapping_object != 0) {
7331 vdev_t *vd = spa->spa_root_vdev->vdev_child[scip->scip_vdev];
7332 ASSERT(scip->scip_prev_obsolete_sm_object != 0);
7333 ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
7335 (void) printf("Condensing indirect vdev %llu: new mapping "
7336 "object %llu, prev obsolete sm %llu\n",
7337 (u_longlong_t)scip->scip_vdev,
7338 (u_longlong_t)scip->scip_next_mapping_object,
7339 (u_longlong_t)scip->scip_prev_obsolete_sm_object);
7340 if (scip->scip_prev_obsolete_sm_object != 0) {
7341 space_map_t *prev_obsolete_sm = NULL;
7342 VERIFY0(space_map_open(&prev_obsolete_sm,
7343 spa->spa_meta_objset,
7344 scip->scip_prev_obsolete_sm_object,
7345 0, vd->vdev_asize, 0));
7346 dump_spacemap(spa->spa_meta_objset, prev_obsolete_sm);
7347 (void) printf("\n");
7348 space_map_close(prev_obsolete_sm);
7351 scip_count += 2;
7354 for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
7355 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
7356 vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
7358 if (vic->vic_mapping_object != 0) {
7359 ASSERT(vd->vdev_ops == &vdev_indirect_ops ||
7360 vd->vdev_removing);
7361 indirect_vdev_count++;
7363 if (vd->vdev_indirect_mapping->vim_havecounts) {
7364 obsolete_counts_count++;
7368 boolean_t are_precise;
7369 VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
7370 if (are_precise) {
7371 ASSERT(vic->vic_mapping_object != 0);
7372 precise_vdev_count++;
7375 uint64_t obsolete_sm_object;
7376 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
7377 if (obsolete_sm_object != 0) {
7378 ASSERT(vic->vic_mapping_object != 0);
7379 obsolete_sm_count++;
7383 (void) feature_get_refcount(spa,
7384 &spa_feature_table[SPA_FEATURE_DEVICE_REMOVAL],
7385 &dr_feature_refcount);
7386 (void) feature_get_refcount(spa,
7387 &spa_feature_table[SPA_FEATURE_OBSOLETE_COUNTS],
7388 &oc_feature_refcount);
7390 if (dr_feature_refcount != indirect_vdev_count) {
7391 ret = 1;
7392 (void) printf("Number of indirect vdevs (%llu) " \
7393 "does not match feature count (%llu)\n",
7394 (u_longlong_t)indirect_vdev_count,
7395 (u_longlong_t)dr_feature_refcount);
7396 } else {
7397 (void) printf("Verified device_removal feature refcount " \
7398 "of %llu is correct\n",
7399 (u_longlong_t)dr_feature_refcount);
7402 if (zap_contains(spa_meta_objset(spa), DMU_POOL_DIRECTORY_OBJECT,
7403 DMU_POOL_OBSOLETE_BPOBJ) == 0) {
7404 obsolete_bpobj_count++;
7408 obsolete_counts_object_count = precise_vdev_count;
7409 obsolete_counts_object_count += obsolete_sm_count;
7410 obsolete_counts_object_count += obsolete_counts_count;
7411 obsolete_counts_object_count += scip_count;
7412 obsolete_counts_object_count += obsolete_bpobj_count;
7413 obsolete_counts_object_count += remap_deadlist_count;
7415 if (oc_feature_refcount != obsolete_counts_object_count) {
7416 ret = 1;
7417 (void) printf("Number of obsolete counts objects (%llu) " \
7418 "does not match feature count (%llu)\n",
7419 (u_longlong_t)obsolete_counts_object_count,
7420 (u_longlong_t)oc_feature_refcount);
7421 (void) printf("pv:%llu os:%llu oc:%llu sc:%llu "
7422 "ob:%llu rd:%llu\n",
7423 (u_longlong_t)precise_vdev_count,
7424 (u_longlong_t)obsolete_sm_count,
7425 (u_longlong_t)obsolete_counts_count,
7426 (u_longlong_t)scip_count,
7427 (u_longlong_t)obsolete_bpobj_count,
7428 (u_longlong_t)remap_deadlist_count);
7429 } else {
7430 (void) printf("Verified indirect_refcount feature refcount " \
7431 "of %llu is correct\n",
7432 (u_longlong_t)oc_feature_refcount);
7434 return (ret);
7437 static void
7438 zdb_set_skip_mmp(char *target)
7440 spa_t *spa;
7443 * Disable the activity check to allow examination of
7444 * active pools.
7446 mutex_enter(&spa_namespace_lock);
7447 if ((spa = spa_lookup(target)) != NULL) {
7448 spa->spa_import_flags |= ZFS_IMPORT_SKIP_MMP;
7450 mutex_exit(&spa_namespace_lock);
7453 #define BOGUS_SUFFIX "_CHECKPOINTED_UNIVERSE"
7455 * Import the checkpointed state of the pool specified by the target
7456 * parameter as readonly. The function also accepts a pool config
7457 * as an optional parameter, else it attempts to infer the config by
7458 * the name of the target pool.
7460 * Note that the checkpointed state's pool name will be the name of
7461 * the original pool with the above suffix appended to it. In addition,
7462 * if the target is not a pool name (e.g. a path to a dataset) then
7463 * the new_path parameter is populated with the updated path to
7464 * reflect the fact that we are looking into the checkpointed state.
7466 * The function returns a newly-allocated copy of the name of the
7467 * pool containing the checkpointed state. When this copy is no
7468 * longer needed it should be freed with free(3C). Same thing
7469 * applies to the new_path parameter if allocated.
7471 static char *
7472 import_checkpointed_state(char *target, nvlist_t *cfg, char **new_path)
7474 int error = 0;
7475 char *poolname, *bogus_name = NULL;
7476 boolean_t freecfg = B_FALSE;
7478 /* If the target is not a pool, the extract the pool name */
7479 char *path_start = strchr(target, '/');
7480 if (path_start != NULL) {
7481 size_t poolname_len = path_start - target;
7482 poolname = strndup(target, poolname_len);
7483 } else {
7484 poolname = target;
7487 if (cfg == NULL) {
7488 zdb_set_skip_mmp(poolname);
7489 error = spa_get_stats(poolname, &cfg, NULL, 0);
7490 if (error != 0) {
7491 fatal("Tried to read config of pool \"%s\" but "
7492 "spa_get_stats() failed with error %d\n",
7493 poolname, error);
7495 freecfg = B_TRUE;
7498 if (asprintf(&bogus_name, "%s%s", poolname, BOGUS_SUFFIX) == -1) {
7499 if (target != poolname)
7500 free(poolname);
7501 return (NULL);
7503 fnvlist_add_string(cfg, ZPOOL_CONFIG_POOL_NAME, bogus_name);
7505 error = spa_import(bogus_name, cfg, NULL,
7506 ZFS_IMPORT_MISSING_LOG | ZFS_IMPORT_CHECKPOINT |
7507 ZFS_IMPORT_SKIP_MMP);
7508 if (freecfg)
7509 nvlist_free(cfg);
7510 if (error != 0) {
7511 fatal("Tried to import pool \"%s\" but spa_import() failed "
7512 "with error %d\n", bogus_name, error);
7515 if (new_path != NULL && path_start != NULL) {
7516 if (asprintf(new_path, "%s%s", bogus_name, path_start) == -1) {
7517 free(bogus_name);
7518 if (path_start != NULL)
7519 free(poolname);
7520 return (NULL);
7524 if (target != poolname)
7525 free(poolname);
7527 return (bogus_name);
7530 typedef struct verify_checkpoint_sm_entry_cb_arg {
7531 vdev_t *vcsec_vd;
7533 /* the following fields are only used for printing progress */
7534 uint64_t vcsec_entryid;
7535 uint64_t vcsec_num_entries;
7536 } verify_checkpoint_sm_entry_cb_arg_t;
7538 #define ENTRIES_PER_PROGRESS_UPDATE 10000
7540 static int
7541 verify_checkpoint_sm_entry_cb(space_map_entry_t *sme, void *arg)
7543 verify_checkpoint_sm_entry_cb_arg_t *vcsec = arg;
7544 vdev_t *vd = vcsec->vcsec_vd;
7545 metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
7546 uint64_t end = sme->sme_offset + sme->sme_run;
7548 ASSERT(sme->sme_type == SM_FREE);
7550 if ((vcsec->vcsec_entryid % ENTRIES_PER_PROGRESS_UPDATE) == 0) {
7551 (void) fprintf(stderr,
7552 "\rverifying vdev %llu, space map entry %llu of %llu ...",
7553 (longlong_t)vd->vdev_id,
7554 (longlong_t)vcsec->vcsec_entryid,
7555 (longlong_t)vcsec->vcsec_num_entries);
7557 vcsec->vcsec_entryid++;
7560 * See comment in checkpoint_sm_exclude_entry_cb()
7562 VERIFY3U(sme->sme_offset, >=, ms->ms_start);
7563 VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
7566 * The entries in the vdev_checkpoint_sm should be marked as
7567 * allocated in the checkpointed state of the pool, therefore
7568 * their respective ms_allocateable trees should not contain them.
7570 mutex_enter(&ms->ms_lock);
7571 range_tree_verify_not_present(ms->ms_allocatable,
7572 sme->sme_offset, sme->sme_run);
7573 mutex_exit(&ms->ms_lock);
7575 return (0);
7579 * Verify that all segments in the vdev_checkpoint_sm are allocated
7580 * according to the checkpoint's ms_sm (i.e. are not in the checkpoint's
7581 * ms_allocatable).
7583 * Do so by comparing the checkpoint space maps (vdev_checkpoint_sm) of
7584 * each vdev in the current state of the pool to the metaslab space maps
7585 * (ms_sm) of the checkpointed state of the pool.
7587 * Note that the function changes the state of the ms_allocatable
7588 * trees of the current spa_t. The entries of these ms_allocatable
7589 * trees are cleared out and then repopulated from with the free
7590 * entries of their respective ms_sm space maps.
7592 static void
7593 verify_checkpoint_vdev_spacemaps(spa_t *checkpoint, spa_t *current)
7595 vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
7596 vdev_t *current_rvd = current->spa_root_vdev;
7598 load_concrete_ms_allocatable_trees(checkpoint, SM_FREE);
7600 for (uint64_t c = 0; c < ckpoint_rvd->vdev_children; c++) {
7601 vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[c];
7602 vdev_t *current_vd = current_rvd->vdev_child[c];
7604 space_map_t *checkpoint_sm = NULL;
7605 uint64_t checkpoint_sm_obj;
7607 if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
7609 * Since we don't allow device removal in a pool
7610 * that has a checkpoint, we expect that all removed
7611 * vdevs were removed from the pool before the
7612 * checkpoint.
7614 ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
7615 continue;
7619 * If the checkpoint space map doesn't exist, then nothing
7620 * here is checkpointed so there's nothing to verify.
7622 if (current_vd->vdev_top_zap == 0 ||
7623 zap_contains(spa_meta_objset(current),
7624 current_vd->vdev_top_zap,
7625 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
7626 continue;
7628 VERIFY0(zap_lookup(spa_meta_objset(current),
7629 current_vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
7630 sizeof (uint64_t), 1, &checkpoint_sm_obj));
7632 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(current),
7633 checkpoint_sm_obj, 0, current_vd->vdev_asize,
7634 current_vd->vdev_ashift));
7636 verify_checkpoint_sm_entry_cb_arg_t vcsec;
7637 vcsec.vcsec_vd = ckpoint_vd;
7638 vcsec.vcsec_entryid = 0;
7639 vcsec.vcsec_num_entries =
7640 space_map_length(checkpoint_sm) / sizeof (uint64_t);
7641 VERIFY0(space_map_iterate(checkpoint_sm,
7642 space_map_length(checkpoint_sm),
7643 verify_checkpoint_sm_entry_cb, &vcsec));
7644 if (dump_opt['m'] > 3)
7645 dump_spacemap(current->spa_meta_objset, checkpoint_sm);
7646 space_map_close(checkpoint_sm);
7650 * If we've added vdevs since we took the checkpoint, ensure
7651 * that their checkpoint space maps are empty.
7653 if (ckpoint_rvd->vdev_children < current_rvd->vdev_children) {
7654 for (uint64_t c = ckpoint_rvd->vdev_children;
7655 c < current_rvd->vdev_children; c++) {
7656 vdev_t *current_vd = current_rvd->vdev_child[c];
7657 VERIFY3P(current_vd->vdev_checkpoint_sm, ==, NULL);
7661 /* for cleaner progress output */
7662 (void) fprintf(stderr, "\n");
7666 * Verifies that all space that's allocated in the checkpoint is
7667 * still allocated in the current version, by checking that everything
7668 * in checkpoint's ms_allocatable (which is actually allocated, not
7669 * allocatable/free) is not present in current's ms_allocatable.
7671 * Note that the function changes the state of the ms_allocatable
7672 * trees of both spas when called. The entries of all ms_allocatable
7673 * trees are cleared out and then repopulated from their respective
7674 * ms_sm space maps. In the checkpointed state we load the allocated
7675 * entries, and in the current state we load the free entries.
7677 static void
7678 verify_checkpoint_ms_spacemaps(spa_t *checkpoint, spa_t *current)
7680 vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
7681 vdev_t *current_rvd = current->spa_root_vdev;
7683 load_concrete_ms_allocatable_trees(checkpoint, SM_ALLOC);
7684 load_concrete_ms_allocatable_trees(current, SM_FREE);
7686 for (uint64_t i = 0; i < ckpoint_rvd->vdev_children; i++) {
7687 vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[i];
7688 vdev_t *current_vd = current_rvd->vdev_child[i];
7690 if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
7692 * See comment in verify_checkpoint_vdev_spacemaps()
7694 ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
7695 continue;
7698 for (uint64_t m = 0; m < ckpoint_vd->vdev_ms_count; m++) {
7699 metaslab_t *ckpoint_msp = ckpoint_vd->vdev_ms[m];
7700 metaslab_t *current_msp = current_vd->vdev_ms[m];
7702 (void) fprintf(stderr,
7703 "\rverifying vdev %llu of %llu, "
7704 "metaslab %llu of %llu ...",
7705 (longlong_t)current_vd->vdev_id,
7706 (longlong_t)current_rvd->vdev_children,
7707 (longlong_t)current_vd->vdev_ms[m]->ms_id,
7708 (longlong_t)current_vd->vdev_ms_count);
7711 * We walk through the ms_allocatable trees that
7712 * are loaded with the allocated blocks from the
7713 * ms_sm spacemaps of the checkpoint. For each
7714 * one of these ranges we ensure that none of them
7715 * exists in the ms_allocatable trees of the
7716 * current state which are loaded with the ranges
7717 * that are currently free.
7719 * This way we ensure that none of the blocks that
7720 * are part of the checkpoint were freed by mistake.
7722 range_tree_walk(ckpoint_msp->ms_allocatable,
7723 (range_tree_func_t *)range_tree_verify_not_present,
7724 current_msp->ms_allocatable);
7728 /* for cleaner progress output */
7729 (void) fprintf(stderr, "\n");
7732 static void
7733 verify_checkpoint_blocks(spa_t *spa)
7735 ASSERT(!dump_opt['L']);
7737 spa_t *checkpoint_spa;
7738 char *checkpoint_pool;
7739 int error = 0;
7742 * We import the checkpointed state of the pool (under a different
7743 * name) so we can do verification on it against the current state
7744 * of the pool.
7746 checkpoint_pool = import_checkpointed_state(spa->spa_name, NULL,
7747 NULL);
7748 ASSERT(strcmp(spa->spa_name, checkpoint_pool) != 0);
7750 error = spa_open(checkpoint_pool, &checkpoint_spa, FTAG);
7751 if (error != 0) {
7752 fatal("Tried to open pool \"%s\" but spa_open() failed with "
7753 "error %d\n", checkpoint_pool, error);
7757 * Ensure that ranges in the checkpoint space maps of each vdev
7758 * are allocated according to the checkpointed state's metaslab
7759 * space maps.
7761 verify_checkpoint_vdev_spacemaps(checkpoint_spa, spa);
7764 * Ensure that allocated ranges in the checkpoint's metaslab
7765 * space maps remain allocated in the metaslab space maps of
7766 * the current state.
7768 verify_checkpoint_ms_spacemaps(checkpoint_spa, spa);
7771 * Once we are done, we get rid of the checkpointed state.
7773 spa_close(checkpoint_spa, FTAG);
7774 free(checkpoint_pool);
7777 static void
7778 dump_leftover_checkpoint_blocks(spa_t *spa)
7780 vdev_t *rvd = spa->spa_root_vdev;
7782 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
7783 vdev_t *vd = rvd->vdev_child[i];
7785 space_map_t *checkpoint_sm = NULL;
7786 uint64_t checkpoint_sm_obj;
7788 if (vd->vdev_top_zap == 0)
7789 continue;
7791 if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
7792 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
7793 continue;
7795 VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
7796 VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
7797 sizeof (uint64_t), 1, &checkpoint_sm_obj));
7799 VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
7800 checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
7801 dump_spacemap(spa->spa_meta_objset, checkpoint_sm);
7802 space_map_close(checkpoint_sm);
7806 static int
7807 verify_checkpoint(spa_t *spa)
7809 uberblock_t checkpoint;
7810 int error;
7812 if (!spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT))
7813 return (0);
7815 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7816 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
7817 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
7819 if (error == ENOENT && !dump_opt['L']) {
7821 * If the feature is active but the uberblock is missing
7822 * then we must be in the middle of discarding the
7823 * checkpoint.
7825 (void) printf("\nPartially discarded checkpoint "
7826 "state found:\n");
7827 if (dump_opt['m'] > 3)
7828 dump_leftover_checkpoint_blocks(spa);
7829 return (0);
7830 } else if (error != 0) {
7831 (void) printf("lookup error %d when looking for "
7832 "checkpointed uberblock in MOS\n", error);
7833 return (error);
7835 dump_uberblock(&checkpoint, "\nCheckpointed uberblock found:\n", "\n");
7837 if (checkpoint.ub_checkpoint_txg == 0) {
7838 (void) printf("\nub_checkpoint_txg not set in checkpointed "
7839 "uberblock\n");
7840 error = 3;
7843 if (error == 0 && !dump_opt['L'])
7844 verify_checkpoint_blocks(spa);
7846 return (error);
7849 static void
7850 mos_leaks_cb(void *arg, uint64_t start, uint64_t size)
7852 (void) arg;
7853 for (uint64_t i = start; i < size; i++) {
7854 (void) printf("MOS object %llu referenced but not allocated\n",
7855 (u_longlong_t)i);
7859 static void
7860 mos_obj_refd(uint64_t obj)
7862 if (obj != 0 && mos_refd_objs != NULL)
7863 range_tree_add(mos_refd_objs, obj, 1);
7867 * Call on a MOS object that may already have been referenced.
7869 static void
7870 mos_obj_refd_multiple(uint64_t obj)
7872 if (obj != 0 && mos_refd_objs != NULL &&
7873 !range_tree_contains(mos_refd_objs, obj, 1))
7874 range_tree_add(mos_refd_objs, obj, 1);
7877 static void
7878 mos_leak_vdev_top_zap(vdev_t *vd)
7880 uint64_t ms_flush_data_obj;
7881 int error = zap_lookup(spa_meta_objset(vd->vdev_spa),
7882 vd->vdev_top_zap, VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS,
7883 sizeof (ms_flush_data_obj), 1, &ms_flush_data_obj);
7884 if (error == ENOENT)
7885 return;
7886 ASSERT0(error);
7888 mos_obj_refd(ms_flush_data_obj);
7891 static void
7892 mos_leak_vdev(vdev_t *vd)
7894 mos_obj_refd(vd->vdev_dtl_object);
7895 mos_obj_refd(vd->vdev_ms_array);
7896 mos_obj_refd(vd->vdev_indirect_config.vic_births_object);
7897 mos_obj_refd(vd->vdev_indirect_config.vic_mapping_object);
7898 mos_obj_refd(vd->vdev_leaf_zap);
7899 if (vd->vdev_checkpoint_sm != NULL)
7900 mos_obj_refd(vd->vdev_checkpoint_sm->sm_object);
7901 if (vd->vdev_indirect_mapping != NULL) {
7902 mos_obj_refd(vd->vdev_indirect_mapping->
7903 vim_phys->vimp_counts_object);
7905 if (vd->vdev_obsolete_sm != NULL)
7906 mos_obj_refd(vd->vdev_obsolete_sm->sm_object);
7908 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
7909 metaslab_t *ms = vd->vdev_ms[m];
7910 mos_obj_refd(space_map_object(ms->ms_sm));
7913 if (vd->vdev_root_zap != 0)
7914 mos_obj_refd(vd->vdev_root_zap);
7916 if (vd->vdev_top_zap != 0) {
7917 mos_obj_refd(vd->vdev_top_zap);
7918 mos_leak_vdev_top_zap(vd);
7921 for (uint64_t c = 0; c < vd->vdev_children; c++) {
7922 mos_leak_vdev(vd->vdev_child[c]);
7926 static void
7927 mos_leak_log_spacemaps(spa_t *spa)
7929 uint64_t spacemap_zap;
7930 int error = zap_lookup(spa_meta_objset(spa),
7931 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_LOG_SPACEMAP_ZAP,
7932 sizeof (spacemap_zap), 1, &spacemap_zap);
7933 if (error == ENOENT)
7934 return;
7935 ASSERT0(error);
7937 mos_obj_refd(spacemap_zap);
7938 for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
7939 sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls))
7940 mos_obj_refd(sls->sls_sm_obj);
7943 static void
7944 errorlog_count_refd(objset_t *mos, uint64_t errlog)
7946 zap_cursor_t zc;
7947 zap_attribute_t za;
7948 for (zap_cursor_init(&zc, mos, errlog);
7949 zap_cursor_retrieve(&zc, &za) == 0;
7950 zap_cursor_advance(&zc)) {
7951 mos_obj_refd(za.za_first_integer);
7953 zap_cursor_fini(&zc);
7956 static int
7957 dump_mos_leaks(spa_t *spa)
7959 int rv = 0;
7960 objset_t *mos = spa->spa_meta_objset;
7961 dsl_pool_t *dp = spa->spa_dsl_pool;
7963 /* Visit and mark all referenced objects in the MOS */
7965 mos_obj_refd(DMU_POOL_DIRECTORY_OBJECT);
7966 mos_obj_refd(spa->spa_pool_props_object);
7967 mos_obj_refd(spa->spa_config_object);
7968 mos_obj_refd(spa->spa_ddt_stat_object);
7969 mos_obj_refd(spa->spa_feat_desc_obj);
7970 mos_obj_refd(spa->spa_feat_enabled_txg_obj);
7971 mos_obj_refd(spa->spa_feat_for_read_obj);
7972 mos_obj_refd(spa->spa_feat_for_write_obj);
7973 mos_obj_refd(spa->spa_history);
7974 mos_obj_refd(spa->spa_errlog_last);
7975 mos_obj_refd(spa->spa_errlog_scrub);
7977 if (spa_feature_is_enabled(spa, SPA_FEATURE_HEAD_ERRLOG)) {
7978 errorlog_count_refd(mos, spa->spa_errlog_last);
7979 errorlog_count_refd(mos, spa->spa_errlog_scrub);
7982 mos_obj_refd(spa->spa_all_vdev_zaps);
7983 mos_obj_refd(spa->spa_dsl_pool->dp_bptree_obj);
7984 mos_obj_refd(spa->spa_dsl_pool->dp_tmp_userrefs_obj);
7985 mos_obj_refd(spa->spa_dsl_pool->dp_scan->scn_phys.scn_queue_obj);
7986 bpobj_count_refd(&spa->spa_deferred_bpobj);
7987 mos_obj_refd(dp->dp_empty_bpobj);
7988 bpobj_count_refd(&dp->dp_obsolete_bpobj);
7989 bpobj_count_refd(&dp->dp_free_bpobj);
7990 mos_obj_refd(spa->spa_l2cache.sav_object);
7991 mos_obj_refd(spa->spa_spares.sav_object);
7993 if (spa->spa_syncing_log_sm != NULL)
7994 mos_obj_refd(spa->spa_syncing_log_sm->sm_object);
7995 mos_leak_log_spacemaps(spa);
7997 mos_obj_refd(spa->spa_condensing_indirect_phys.
7998 scip_next_mapping_object);
7999 mos_obj_refd(spa->spa_condensing_indirect_phys.
8000 scip_prev_obsolete_sm_object);
8001 if (spa->spa_condensing_indirect_phys.scip_next_mapping_object != 0) {
8002 vdev_indirect_mapping_t *vim =
8003 vdev_indirect_mapping_open(mos,
8004 spa->spa_condensing_indirect_phys.scip_next_mapping_object);
8005 mos_obj_refd(vim->vim_phys->vimp_counts_object);
8006 vdev_indirect_mapping_close(vim);
8008 deleted_livelists_dump_mos(spa);
8010 if (dp->dp_origin_snap != NULL) {
8011 dsl_dataset_t *ds;
8013 dsl_pool_config_enter(dp, FTAG);
8014 VERIFY0(dsl_dataset_hold_obj(dp,
8015 dsl_dataset_phys(dp->dp_origin_snap)->ds_next_snap_obj,
8016 FTAG, &ds));
8017 count_ds_mos_objects(ds);
8018 dump_blkptr_list(&ds->ds_deadlist, "Deadlist");
8019 dsl_dataset_rele(ds, FTAG);
8020 dsl_pool_config_exit(dp, FTAG);
8022 count_ds_mos_objects(dp->dp_origin_snap);
8023 dump_blkptr_list(&dp->dp_origin_snap->ds_deadlist, "Deadlist");
8025 count_dir_mos_objects(dp->dp_mos_dir);
8026 if (dp->dp_free_dir != NULL)
8027 count_dir_mos_objects(dp->dp_free_dir);
8028 if (dp->dp_leak_dir != NULL)
8029 count_dir_mos_objects(dp->dp_leak_dir);
8031 mos_leak_vdev(spa->spa_root_vdev);
8033 for (uint64_t class = 0; class < DDT_CLASSES; class++) {
8034 for (uint64_t type = 0; type < DDT_TYPES; type++) {
8035 for (uint64_t cksum = 0;
8036 cksum < ZIO_CHECKSUM_FUNCTIONS; cksum++) {
8037 ddt_t *ddt = spa->spa_ddt[cksum];
8038 mos_obj_refd(ddt->ddt_object[type][class]);
8044 * Visit all allocated objects and make sure they are referenced.
8046 uint64_t object = 0;
8047 while (dmu_object_next(mos, &object, B_FALSE, 0) == 0) {
8048 if (range_tree_contains(mos_refd_objs, object, 1)) {
8049 range_tree_remove(mos_refd_objs, object, 1);
8050 } else {
8051 dmu_object_info_t doi;
8052 const char *name;
8053 VERIFY0(dmu_object_info(mos, object, &doi));
8054 if (doi.doi_type & DMU_OT_NEWTYPE) {
8055 dmu_object_byteswap_t bswap =
8056 DMU_OT_BYTESWAP(doi.doi_type);
8057 name = dmu_ot_byteswap[bswap].ob_name;
8058 } else {
8059 name = dmu_ot[doi.doi_type].ot_name;
8062 (void) printf("MOS object %llu (%s) leaked\n",
8063 (u_longlong_t)object, name);
8064 rv = 2;
8067 (void) range_tree_walk(mos_refd_objs, mos_leaks_cb, NULL);
8068 if (!range_tree_is_empty(mos_refd_objs))
8069 rv = 2;
8070 range_tree_vacate(mos_refd_objs, NULL, NULL);
8071 range_tree_destroy(mos_refd_objs);
8072 return (rv);
8075 typedef struct log_sm_obsolete_stats_arg {
8076 uint64_t lsos_current_txg;
8078 uint64_t lsos_total_entries;
8079 uint64_t lsos_valid_entries;
8081 uint64_t lsos_sm_entries;
8082 uint64_t lsos_valid_sm_entries;
8083 } log_sm_obsolete_stats_arg_t;
8085 static int
8086 log_spacemap_obsolete_stats_cb(spa_t *spa, space_map_entry_t *sme,
8087 uint64_t txg, void *arg)
8089 log_sm_obsolete_stats_arg_t *lsos = arg;
8091 uint64_t offset = sme->sme_offset;
8092 uint64_t vdev_id = sme->sme_vdev;
8094 if (lsos->lsos_current_txg == 0) {
8095 /* this is the first log */
8096 lsos->lsos_current_txg = txg;
8097 } else if (lsos->lsos_current_txg < txg) {
8098 /* we just changed log - print stats and reset */
8099 (void) printf("%-8llu valid entries out of %-8llu - txg %llu\n",
8100 (u_longlong_t)lsos->lsos_valid_sm_entries,
8101 (u_longlong_t)lsos->lsos_sm_entries,
8102 (u_longlong_t)lsos->lsos_current_txg);
8103 lsos->lsos_valid_sm_entries = 0;
8104 lsos->lsos_sm_entries = 0;
8105 lsos->lsos_current_txg = txg;
8107 ASSERT3U(lsos->lsos_current_txg, ==, txg);
8109 lsos->lsos_sm_entries++;
8110 lsos->lsos_total_entries++;
8112 vdev_t *vd = vdev_lookup_top(spa, vdev_id);
8113 if (!vdev_is_concrete(vd))
8114 return (0);
8116 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
8117 ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
8119 if (txg < metaslab_unflushed_txg(ms))
8120 return (0);
8121 lsos->lsos_valid_sm_entries++;
8122 lsos->lsos_valid_entries++;
8123 return (0);
8126 static void
8127 dump_log_spacemap_obsolete_stats(spa_t *spa)
8129 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
8130 return;
8132 log_sm_obsolete_stats_arg_t lsos = {0};
8134 (void) printf("Log Space Map Obsolete Entry Statistics:\n");
8136 iterate_through_spacemap_logs(spa,
8137 log_spacemap_obsolete_stats_cb, &lsos);
8139 /* print stats for latest log */
8140 (void) printf("%-8llu valid entries out of %-8llu - txg %llu\n",
8141 (u_longlong_t)lsos.lsos_valid_sm_entries,
8142 (u_longlong_t)lsos.lsos_sm_entries,
8143 (u_longlong_t)lsos.lsos_current_txg);
8145 (void) printf("%-8llu valid entries out of %-8llu - total\n\n",
8146 (u_longlong_t)lsos.lsos_valid_entries,
8147 (u_longlong_t)lsos.lsos_total_entries);
8150 static void
8151 dump_zpool(spa_t *spa)
8153 dsl_pool_t *dp = spa_get_dsl(spa);
8154 int rc = 0;
8156 if (dump_opt['y']) {
8157 livelist_metaslab_validate(spa);
8160 if (dump_opt['S']) {
8161 dump_simulated_ddt(spa);
8162 return;
8165 if (!dump_opt['e'] && dump_opt['C'] > 1) {
8166 (void) printf("\nCached configuration:\n");
8167 dump_nvlist(spa->spa_config, 8);
8170 if (dump_opt['C'])
8171 dump_config(spa);
8173 if (dump_opt['u'])
8174 dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
8176 if (dump_opt['D'])
8177 dump_all_ddts(spa);
8179 if (dump_opt['T'])
8180 dump_brt(spa);
8182 if (dump_opt['d'] > 2 || dump_opt['m'])
8183 dump_metaslabs(spa);
8184 if (dump_opt['M'])
8185 dump_metaslab_groups(spa, dump_opt['M'] > 1);
8186 if (dump_opt['d'] > 2 || dump_opt['m']) {
8187 dump_log_spacemaps(spa);
8188 dump_log_spacemap_obsolete_stats(spa);
8191 if (dump_opt['d'] || dump_opt['i']) {
8192 spa_feature_t f;
8193 mos_refd_objs = range_tree_create(NULL, RANGE_SEG64, NULL, 0,
8195 dump_objset(dp->dp_meta_objset);
8197 if (dump_opt['d'] >= 3) {
8198 dsl_pool_t *dp = spa->spa_dsl_pool;
8199 dump_full_bpobj(&spa->spa_deferred_bpobj,
8200 "Deferred frees", 0);
8201 if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
8202 dump_full_bpobj(&dp->dp_free_bpobj,
8203 "Pool snapshot frees", 0);
8205 if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
8206 ASSERT(spa_feature_is_enabled(spa,
8207 SPA_FEATURE_DEVICE_REMOVAL));
8208 dump_full_bpobj(&dp->dp_obsolete_bpobj,
8209 "Pool obsolete blocks", 0);
8212 if (spa_feature_is_active(spa,
8213 SPA_FEATURE_ASYNC_DESTROY)) {
8214 dump_bptree(spa->spa_meta_objset,
8215 dp->dp_bptree_obj,
8216 "Pool dataset frees");
8218 dump_dtl(spa->spa_root_vdev, 0);
8221 for (spa_feature_t f = 0; f < SPA_FEATURES; f++)
8222 global_feature_count[f] = UINT64_MAX;
8223 global_feature_count[SPA_FEATURE_REDACTION_BOOKMARKS] = 0;
8224 global_feature_count[SPA_FEATURE_BOOKMARK_WRITTEN] = 0;
8225 global_feature_count[SPA_FEATURE_LIVELIST] = 0;
8227 (void) dmu_objset_find(spa_name(spa), dump_one_objset,
8228 NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
8230 if (rc == 0 && !dump_opt['L'])
8231 rc = dump_mos_leaks(spa);
8233 for (f = 0; f < SPA_FEATURES; f++) {
8234 uint64_t refcount;
8236 uint64_t *arr;
8237 if (!(spa_feature_table[f].fi_flags &
8238 ZFEATURE_FLAG_PER_DATASET)) {
8239 if (global_feature_count[f] == UINT64_MAX)
8240 continue;
8241 if (!spa_feature_is_enabled(spa, f)) {
8242 ASSERT0(global_feature_count[f]);
8243 continue;
8245 arr = global_feature_count;
8246 } else {
8247 if (!spa_feature_is_enabled(spa, f)) {
8248 ASSERT0(dataset_feature_count[f]);
8249 continue;
8251 arr = dataset_feature_count;
8253 if (feature_get_refcount(spa, &spa_feature_table[f],
8254 &refcount) == ENOTSUP)
8255 continue;
8256 if (arr[f] != refcount) {
8257 (void) printf("%s feature refcount mismatch: "
8258 "%lld consumers != %lld refcount\n",
8259 spa_feature_table[f].fi_uname,
8260 (longlong_t)arr[f], (longlong_t)refcount);
8261 rc = 2;
8262 } else {
8263 (void) printf("Verified %s feature refcount "
8264 "of %llu is correct\n",
8265 spa_feature_table[f].fi_uname,
8266 (longlong_t)refcount);
8270 if (rc == 0)
8271 rc = verify_device_removal_feature_counts(spa);
8274 if (rc == 0 && (dump_opt['b'] || dump_opt['c']))
8275 rc = dump_block_stats(spa);
8277 if (rc == 0)
8278 rc = verify_spacemap_refcounts(spa);
8280 if (dump_opt['s'])
8281 show_pool_stats(spa);
8283 if (dump_opt['h'])
8284 dump_history(spa);
8286 if (rc == 0)
8287 rc = verify_checkpoint(spa);
8289 if (rc != 0) {
8290 dump_debug_buffer();
8291 exit(rc);
8295 #define ZDB_FLAG_CHECKSUM 0x0001
8296 #define ZDB_FLAG_DECOMPRESS 0x0002
8297 #define ZDB_FLAG_BSWAP 0x0004
8298 #define ZDB_FLAG_GBH 0x0008
8299 #define ZDB_FLAG_INDIRECT 0x0010
8300 #define ZDB_FLAG_RAW 0x0020
8301 #define ZDB_FLAG_PRINT_BLKPTR 0x0040
8302 #define ZDB_FLAG_VERBOSE 0x0080
8304 static int flagbits[256];
8305 static char flagbitstr[16];
8307 static void
8308 zdb_print_blkptr(const blkptr_t *bp, int flags)
8310 char blkbuf[BP_SPRINTF_LEN];
8312 if (flags & ZDB_FLAG_BSWAP)
8313 byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
8315 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
8316 (void) printf("%s\n", blkbuf);
8319 static void
8320 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
8322 int i;
8324 for (i = 0; i < nbps; i++)
8325 zdb_print_blkptr(&bp[i], flags);
8328 static void
8329 zdb_dump_gbh(void *buf, int flags)
8331 zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
8334 static void
8335 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
8337 if (flags & ZDB_FLAG_BSWAP)
8338 byteswap_uint64_array(buf, size);
8339 VERIFY(write(fileno(stdout), buf, size) == size);
8342 static void
8343 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
8345 uint64_t *d = (uint64_t *)buf;
8346 unsigned nwords = size / sizeof (uint64_t);
8347 int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
8348 unsigned i, j;
8349 const char *hdr;
8350 char *c;
8353 if (do_bswap)
8354 hdr = " 7 6 5 4 3 2 1 0 f e d c b a 9 8";
8355 else
8356 hdr = " 0 1 2 3 4 5 6 7 8 9 a b c d e f";
8358 (void) printf("\n%s\n%6s %s 0123456789abcdef\n", label, "", hdr);
8360 #ifdef _LITTLE_ENDIAN
8361 /* correct the endianness */
8362 do_bswap = !do_bswap;
8363 #endif
8364 for (i = 0; i < nwords; i += 2) {
8365 (void) printf("%06llx: %016llx %016llx ",
8366 (u_longlong_t)(i * sizeof (uint64_t)),
8367 (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
8368 (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
8370 c = (char *)&d[i];
8371 for (j = 0; j < 2 * sizeof (uint64_t); j++)
8372 (void) printf("%c", isprint(c[j]) ? c[j] : '.');
8373 (void) printf("\n");
8378 * There are two acceptable formats:
8379 * leaf_name - For example: c1t0d0 or /tmp/ztest.0a
8380 * child[.child]* - For example: 0.1.1
8382 * The second form can be used to specify arbitrary vdevs anywhere
8383 * in the hierarchy. For example, in a pool with a mirror of
8384 * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
8386 static vdev_t *
8387 zdb_vdev_lookup(vdev_t *vdev, const char *path)
8389 char *s, *p, *q;
8390 unsigned i;
8392 if (vdev == NULL)
8393 return (NULL);
8395 /* First, assume the x.x.x.x format */
8396 i = strtoul(path, &s, 10);
8397 if (s == path || (s && *s != '.' && *s != '\0'))
8398 goto name;
8399 if (i >= vdev->vdev_children)
8400 return (NULL);
8402 vdev = vdev->vdev_child[i];
8403 if (s && *s == '\0')
8404 return (vdev);
8405 return (zdb_vdev_lookup(vdev, s+1));
8407 name:
8408 for (i = 0; i < vdev->vdev_children; i++) {
8409 vdev_t *vc = vdev->vdev_child[i];
8411 if (vc->vdev_path == NULL) {
8412 vc = zdb_vdev_lookup(vc, path);
8413 if (vc == NULL)
8414 continue;
8415 else
8416 return (vc);
8419 p = strrchr(vc->vdev_path, '/');
8420 p = p ? p + 1 : vc->vdev_path;
8421 q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
8423 if (strcmp(vc->vdev_path, path) == 0)
8424 return (vc);
8425 if (strcmp(p, path) == 0)
8426 return (vc);
8427 if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
8428 return (vc);
8431 return (NULL);
8434 static int
8435 name_from_objset_id(spa_t *spa, uint64_t objset_id, char *outstr)
8437 dsl_dataset_t *ds;
8439 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
8440 int error = dsl_dataset_hold_obj(spa->spa_dsl_pool, objset_id,
8441 NULL, &ds);
8442 if (error != 0) {
8443 (void) fprintf(stderr, "failed to hold objset %llu: %s\n",
8444 (u_longlong_t)objset_id, strerror(error));
8445 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
8446 return (error);
8448 dsl_dataset_name(ds, outstr);
8449 dsl_dataset_rele(ds, NULL);
8450 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
8451 return (0);
8454 static boolean_t
8455 zdb_parse_block_sizes(char *sizes, uint64_t *lsize, uint64_t *psize)
8457 char *s0, *s1, *tmp = NULL;
8459 if (sizes == NULL)
8460 return (B_FALSE);
8462 s0 = strtok_r(sizes, "/", &tmp);
8463 if (s0 == NULL)
8464 return (B_FALSE);
8465 s1 = strtok_r(NULL, "/", &tmp);
8466 *lsize = strtoull(s0, NULL, 16);
8467 *psize = s1 ? strtoull(s1, NULL, 16) : *lsize;
8468 return (*lsize >= *psize && *psize > 0);
8471 #define ZIO_COMPRESS_MASK(alg) (1ULL << (ZIO_COMPRESS_##alg))
8473 static boolean_t
8474 zdb_decompress_block(abd_t *pabd, void *buf, void *lbuf, uint64_t lsize,
8475 uint64_t psize, int flags)
8477 (void) buf;
8478 boolean_t exceeded = B_FALSE;
8480 * We don't know how the data was compressed, so just try
8481 * every decompress function at every inflated blocksize.
8483 void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
8484 int cfuncs[ZIO_COMPRESS_FUNCTIONS] = { 0 };
8485 int *cfuncp = cfuncs;
8486 uint64_t maxlsize = SPA_MAXBLOCKSIZE;
8487 uint64_t mask = ZIO_COMPRESS_MASK(ON) | ZIO_COMPRESS_MASK(OFF) |
8488 ZIO_COMPRESS_MASK(INHERIT) | ZIO_COMPRESS_MASK(EMPTY) |
8489 (getenv("ZDB_NO_ZLE") ? ZIO_COMPRESS_MASK(ZLE) : 0);
8490 *cfuncp++ = ZIO_COMPRESS_LZ4;
8491 *cfuncp++ = ZIO_COMPRESS_LZJB;
8492 mask |= ZIO_COMPRESS_MASK(LZ4) | ZIO_COMPRESS_MASK(LZJB);
8493 for (int c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++)
8494 if (((1ULL << c) & mask) == 0)
8495 *cfuncp++ = c;
8498 * On the one hand, with SPA_MAXBLOCKSIZE at 16MB, this
8499 * could take a while and we should let the user know
8500 * we are not stuck. On the other hand, printing progress
8501 * info gets old after a while. User can specify 'v' flag
8502 * to see the progression.
8504 if (lsize == psize)
8505 lsize += SPA_MINBLOCKSIZE;
8506 else
8507 maxlsize = lsize;
8508 for (; lsize <= maxlsize; lsize += SPA_MINBLOCKSIZE) {
8509 for (cfuncp = cfuncs; *cfuncp; cfuncp++) {
8510 if (flags & ZDB_FLAG_VERBOSE) {
8511 (void) fprintf(stderr,
8512 "Trying %05llx -> %05llx (%s)\n",
8513 (u_longlong_t)psize,
8514 (u_longlong_t)lsize,
8515 zio_compress_table[*cfuncp].\
8516 ci_name);
8520 * We randomize lbuf2, and decompress to both
8521 * lbuf and lbuf2. This way, we will know if
8522 * decompression fill exactly to lsize.
8524 VERIFY0(random_get_pseudo_bytes(lbuf2, lsize));
8526 if (zio_decompress_data(*cfuncp, pabd,
8527 lbuf, psize, lsize, NULL) == 0 &&
8528 zio_decompress_data(*cfuncp, pabd,
8529 lbuf2, psize, lsize, NULL) == 0 &&
8530 memcmp(lbuf, lbuf2, lsize) == 0)
8531 break;
8533 if (*cfuncp != 0)
8534 break;
8536 umem_free(lbuf2, SPA_MAXBLOCKSIZE);
8538 if (lsize > maxlsize) {
8539 exceeded = B_TRUE;
8541 if (*cfuncp == ZIO_COMPRESS_ZLE) {
8542 printf("\nZLE decompression was selected. If you "
8543 "suspect the results are wrong,\ntry avoiding ZLE "
8544 "by setting and exporting ZDB_NO_ZLE=\"true\"\n");
8547 return (exceeded);
8551 * Read a block from a pool and print it out. The syntax of the
8552 * block descriptor is:
8554 * pool:vdev_specifier:offset:[lsize/]psize[:flags]
8556 * pool - The name of the pool you wish to read from
8557 * vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
8558 * offset - offset, in hex, in bytes
8559 * size - Amount of data to read, in hex, in bytes
8560 * flags - A string of characters specifying options
8561 * b: Decode a blkptr at given offset within block
8562 * c: Calculate and display checksums
8563 * d: Decompress data before dumping
8564 * e: Byteswap data before dumping
8565 * g: Display data as a gang block header
8566 * i: Display as an indirect block
8567 * r: Dump raw data to stdout
8568 * v: Verbose
8571 static void
8572 zdb_read_block(char *thing, spa_t *spa)
8574 blkptr_t blk, *bp = &blk;
8575 dva_t *dva = bp->blk_dva;
8576 int flags = 0;
8577 uint64_t offset = 0, psize = 0, lsize = 0, blkptr_offset = 0;
8578 zio_t *zio;
8579 vdev_t *vd;
8580 abd_t *pabd;
8581 void *lbuf, *buf;
8582 char *s, *p, *dup, *flagstr, *sizes, *tmp = NULL;
8583 const char *vdev, *errmsg = NULL;
8584 int i, error;
8585 boolean_t borrowed = B_FALSE, found = B_FALSE;
8587 dup = strdup(thing);
8588 s = strtok_r(dup, ":", &tmp);
8589 vdev = s ?: "";
8590 s = strtok_r(NULL, ":", &tmp);
8591 offset = strtoull(s ? s : "", NULL, 16);
8592 sizes = strtok_r(NULL, ":", &tmp);
8593 s = strtok_r(NULL, ":", &tmp);
8594 flagstr = strdup(s ?: "");
8596 if (!zdb_parse_block_sizes(sizes, &lsize, &psize))
8597 errmsg = "invalid size(s)";
8598 if (!IS_P2ALIGNED(psize, DEV_BSIZE) || !IS_P2ALIGNED(lsize, DEV_BSIZE))
8599 errmsg = "size must be a multiple of sector size";
8600 if (!IS_P2ALIGNED(offset, DEV_BSIZE))
8601 errmsg = "offset must be a multiple of sector size";
8602 if (errmsg) {
8603 (void) printf("Invalid block specifier: %s - %s\n",
8604 thing, errmsg);
8605 goto done;
8608 tmp = NULL;
8609 for (s = strtok_r(flagstr, ":", &tmp);
8610 s != NULL;
8611 s = strtok_r(NULL, ":", &tmp)) {
8612 for (i = 0; i < strlen(flagstr); i++) {
8613 int bit = flagbits[(uchar_t)flagstr[i]];
8615 if (bit == 0) {
8616 (void) printf("***Ignoring flag: %c\n",
8617 (uchar_t)flagstr[i]);
8618 continue;
8620 found = B_TRUE;
8621 flags |= bit;
8623 p = &flagstr[i + 1];
8624 if (*p != ':' && *p != '\0') {
8625 int j = 0, nextbit = flagbits[(uchar_t)*p];
8626 char *end, offstr[8] = { 0 };
8627 if ((bit == ZDB_FLAG_PRINT_BLKPTR) &&
8628 (nextbit == 0)) {
8629 /* look ahead to isolate the offset */
8630 while (nextbit == 0 &&
8631 strchr(flagbitstr, *p) == NULL) {
8632 offstr[j] = *p;
8633 j++;
8634 if (i + j > strlen(flagstr))
8635 break;
8636 p++;
8637 nextbit = flagbits[(uchar_t)*p];
8639 blkptr_offset = strtoull(offstr, &end,
8640 16);
8641 i += j;
8642 } else if (nextbit == 0) {
8643 (void) printf("***Ignoring flag arg:"
8644 " '%c'\n", (uchar_t)*p);
8649 if (blkptr_offset % sizeof (blkptr_t)) {
8650 printf("Block pointer offset 0x%llx "
8651 "must be divisible by 0x%x\n",
8652 (longlong_t)blkptr_offset, (int)sizeof (blkptr_t));
8653 goto done;
8655 if (found == B_FALSE && strlen(flagstr) > 0) {
8656 printf("Invalid flag arg: '%s'\n", flagstr);
8657 goto done;
8660 vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
8661 if (vd == NULL) {
8662 (void) printf("***Invalid vdev: %s\n", vdev);
8663 goto done;
8664 } else {
8665 if (vd->vdev_path)
8666 (void) fprintf(stderr, "Found vdev: %s\n",
8667 vd->vdev_path);
8668 else
8669 (void) fprintf(stderr, "Found vdev type: %s\n",
8670 vd->vdev_ops->vdev_op_type);
8673 pabd = abd_alloc_for_io(SPA_MAXBLOCKSIZE, B_FALSE);
8674 lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
8676 BP_ZERO(bp);
8678 DVA_SET_VDEV(&dva[0], vd->vdev_id);
8679 DVA_SET_OFFSET(&dva[0], offset);
8680 DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
8681 DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
8683 BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
8685 BP_SET_LSIZE(bp, lsize);
8686 BP_SET_PSIZE(bp, psize);
8687 BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
8688 BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
8689 BP_SET_TYPE(bp, DMU_OT_NONE);
8690 BP_SET_LEVEL(bp, 0);
8691 BP_SET_DEDUP(bp, 0);
8692 BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
8694 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8695 zio = zio_root(spa, NULL, NULL, 0);
8697 if (vd == vd->vdev_top) {
8699 * Treat this as a normal block read.
8701 zio_nowait(zio_read(zio, spa, bp, pabd, psize, NULL, NULL,
8702 ZIO_PRIORITY_SYNC_READ,
8703 ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
8704 } else {
8706 * Treat this as a vdev child I/O.
8708 zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pabd,
8709 psize, ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
8710 ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
8711 ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW | ZIO_FLAG_OPTIONAL,
8712 NULL, NULL));
8715 error = zio_wait(zio);
8716 spa_config_exit(spa, SCL_STATE, FTAG);
8718 if (error) {
8719 (void) printf("Read of %s failed, error: %d\n", thing, error);
8720 goto out;
8723 uint64_t orig_lsize = lsize;
8724 buf = lbuf;
8725 if (flags & ZDB_FLAG_DECOMPRESS) {
8726 boolean_t failed = zdb_decompress_block(pabd, buf, lbuf,
8727 lsize, psize, flags);
8728 if (failed) {
8729 (void) printf("Decompress of %s failed\n", thing);
8730 goto out;
8732 } else {
8733 buf = abd_borrow_buf_copy(pabd, lsize);
8734 borrowed = B_TRUE;
8737 * Try to detect invalid block pointer. If invalid, try
8738 * decompressing.
8740 if ((flags & ZDB_FLAG_PRINT_BLKPTR || flags & ZDB_FLAG_INDIRECT) &&
8741 !(flags & ZDB_FLAG_DECOMPRESS)) {
8742 const blkptr_t *b = (const blkptr_t *)(void *)
8743 ((uintptr_t)buf + (uintptr_t)blkptr_offset);
8744 if (zfs_blkptr_verify(spa, b,
8745 BLK_CONFIG_NEEDED, BLK_VERIFY_ONLY) == B_FALSE) {
8746 abd_return_buf_copy(pabd, buf, lsize);
8747 borrowed = B_FALSE;
8748 buf = lbuf;
8749 boolean_t failed = zdb_decompress_block(pabd, buf,
8750 lbuf, lsize, psize, flags);
8751 b = (const blkptr_t *)(void *)
8752 ((uintptr_t)buf + (uintptr_t)blkptr_offset);
8753 if (failed || zfs_blkptr_verify(spa, b,
8754 BLK_CONFIG_NEEDED, BLK_VERIFY_LOG) == B_FALSE) {
8755 printf("invalid block pointer at this DVA\n");
8756 goto out;
8761 if (flags & ZDB_FLAG_PRINT_BLKPTR)
8762 zdb_print_blkptr((blkptr_t *)(void *)
8763 ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
8764 else if (flags & ZDB_FLAG_RAW)
8765 zdb_dump_block_raw(buf, lsize, flags);
8766 else if (flags & ZDB_FLAG_INDIRECT)
8767 zdb_dump_indirect((blkptr_t *)buf,
8768 orig_lsize / sizeof (blkptr_t), flags);
8769 else if (flags & ZDB_FLAG_GBH)
8770 zdb_dump_gbh(buf, flags);
8771 else
8772 zdb_dump_block(thing, buf, lsize, flags);
8775 * If :c was specified, iterate through the checksum table to
8776 * calculate and display each checksum for our specified
8777 * DVA and length.
8779 if ((flags & ZDB_FLAG_CHECKSUM) && !(flags & ZDB_FLAG_RAW) &&
8780 !(flags & ZDB_FLAG_GBH)) {
8781 zio_t *czio;
8782 (void) printf("\n");
8783 for (enum zio_checksum ck = ZIO_CHECKSUM_LABEL;
8784 ck < ZIO_CHECKSUM_FUNCTIONS; ck++) {
8786 if ((zio_checksum_table[ck].ci_flags &
8787 ZCHECKSUM_FLAG_EMBEDDED) ||
8788 ck == ZIO_CHECKSUM_NOPARITY) {
8789 continue;
8791 BP_SET_CHECKSUM(bp, ck);
8792 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8793 czio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
8794 czio->io_bp = bp;
8796 if (vd == vd->vdev_top) {
8797 zio_nowait(zio_read(czio, spa, bp, pabd, psize,
8798 NULL, NULL,
8799 ZIO_PRIORITY_SYNC_READ,
8800 ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW |
8801 ZIO_FLAG_DONT_RETRY, NULL));
8802 } else {
8803 zio_nowait(zio_vdev_child_io(czio, bp, vd,
8804 offset, pabd, psize, ZIO_TYPE_READ,
8805 ZIO_PRIORITY_SYNC_READ,
8806 ZIO_FLAG_DONT_PROPAGATE |
8807 ZIO_FLAG_DONT_RETRY |
8808 ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW |
8809 ZIO_FLAG_SPECULATIVE |
8810 ZIO_FLAG_OPTIONAL, NULL, NULL));
8812 error = zio_wait(czio);
8813 if (error == 0 || error == ECKSUM) {
8814 zio_t *ck_zio = zio_root(spa, NULL, NULL, 0);
8815 ck_zio->io_offset =
8816 DVA_GET_OFFSET(&bp->blk_dva[0]);
8817 ck_zio->io_bp = bp;
8818 zio_checksum_compute(ck_zio, ck, pabd, lsize);
8819 printf(
8820 "%12s\t"
8821 "cksum=%016llx:%016llx:%016llx:%016llx\n",
8822 zio_checksum_table[ck].ci_name,
8823 (u_longlong_t)bp->blk_cksum.zc_word[0],
8824 (u_longlong_t)bp->blk_cksum.zc_word[1],
8825 (u_longlong_t)bp->blk_cksum.zc_word[2],
8826 (u_longlong_t)bp->blk_cksum.zc_word[3]);
8827 zio_wait(ck_zio);
8828 } else {
8829 printf("error %d reading block\n", error);
8831 spa_config_exit(spa, SCL_STATE, FTAG);
8835 if (borrowed)
8836 abd_return_buf_copy(pabd, buf, lsize);
8838 out:
8839 abd_free(pabd);
8840 umem_free(lbuf, SPA_MAXBLOCKSIZE);
8841 done:
8842 free(flagstr);
8843 free(dup);
8846 static void
8847 zdb_embedded_block(char *thing)
8849 blkptr_t bp = {{{{0}}}};
8850 unsigned long long *words = (void *)&bp;
8851 char *buf;
8852 int err;
8854 err = sscanf(thing, "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx:"
8855 "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx",
8856 words + 0, words + 1, words + 2, words + 3,
8857 words + 4, words + 5, words + 6, words + 7,
8858 words + 8, words + 9, words + 10, words + 11,
8859 words + 12, words + 13, words + 14, words + 15);
8860 if (err != 16) {
8861 (void) fprintf(stderr, "invalid input format\n");
8862 exit(1);
8864 ASSERT3U(BPE_GET_LSIZE(&bp), <=, SPA_MAXBLOCKSIZE);
8865 buf = malloc(SPA_MAXBLOCKSIZE);
8866 if (buf == NULL) {
8867 (void) fprintf(stderr, "out of memory\n");
8868 exit(1);
8870 err = decode_embedded_bp(&bp, buf, BPE_GET_LSIZE(&bp));
8871 if (err != 0) {
8872 (void) fprintf(stderr, "decode failed: %u\n", err);
8873 exit(1);
8875 zdb_dump_block_raw(buf, BPE_GET_LSIZE(&bp), 0);
8876 free(buf);
8879 /* check for valid hex or decimal numeric string */
8880 static boolean_t
8881 zdb_numeric(char *str)
8883 int i = 0;
8885 if (strlen(str) == 0)
8886 return (B_FALSE);
8887 if (strncmp(str, "0x", 2) == 0 || strncmp(str, "0X", 2) == 0)
8888 i = 2;
8889 for (; i < strlen(str); i++) {
8890 if (!isxdigit(str[i]))
8891 return (B_FALSE);
8893 return (B_TRUE);
8897 main(int argc, char **argv)
8899 int c;
8900 spa_t *spa = NULL;
8901 objset_t *os = NULL;
8902 int dump_all = 1;
8903 int verbose = 0;
8904 int error = 0;
8905 char **searchdirs = NULL;
8906 int nsearch = 0;
8907 char *target, *target_pool, dsname[ZFS_MAX_DATASET_NAME_LEN];
8908 nvlist_t *policy = NULL;
8909 uint64_t max_txg = UINT64_MAX;
8910 int64_t objset_id = -1;
8911 uint64_t object;
8912 int flags = ZFS_IMPORT_MISSING_LOG;
8913 int rewind = ZPOOL_NEVER_REWIND;
8914 char *spa_config_path_env, *objset_str;
8915 boolean_t target_is_spa = B_TRUE, dataset_lookup = B_FALSE;
8916 nvlist_t *cfg = NULL;
8918 dprintf_setup(&argc, argv);
8921 * If there is an environment variable SPA_CONFIG_PATH it overrides
8922 * default spa_config_path setting. If -U flag is specified it will
8923 * override this environment variable settings once again.
8925 spa_config_path_env = getenv("SPA_CONFIG_PATH");
8926 if (spa_config_path_env != NULL)
8927 spa_config_path = spa_config_path_env;
8930 * For performance reasons, we set this tunable down. We do so before
8931 * the arg parsing section so that the user can override this value if
8932 * they choose.
8934 zfs_btree_verify_intensity = 3;
8936 struct option long_options[] = {
8937 {"ignore-assertions", no_argument, NULL, 'A'},
8938 {"block-stats", no_argument, NULL, 'b'},
8939 {"backup", no_argument, NULL, 'B'},
8940 {"checksum", no_argument, NULL, 'c'},
8941 {"config", no_argument, NULL, 'C'},
8942 {"datasets", no_argument, NULL, 'd'},
8943 {"dedup-stats", no_argument, NULL, 'D'},
8944 {"exported", no_argument, NULL, 'e'},
8945 {"embedded-block-pointer", no_argument, NULL, 'E'},
8946 {"automatic-rewind", no_argument, NULL, 'F'},
8947 {"dump-debug-msg", no_argument, NULL, 'G'},
8948 {"history", no_argument, NULL, 'h'},
8949 {"intent-logs", no_argument, NULL, 'i'},
8950 {"inflight", required_argument, NULL, 'I'},
8951 {"checkpointed-state", no_argument, NULL, 'k'},
8952 {"key", required_argument, NULL, 'K'},
8953 {"label", no_argument, NULL, 'l'},
8954 {"disable-leak-tracking", no_argument, NULL, 'L'},
8955 {"metaslabs", no_argument, NULL, 'm'},
8956 {"metaslab-groups", no_argument, NULL, 'M'},
8957 {"numeric", no_argument, NULL, 'N'},
8958 {"option", required_argument, NULL, 'o'},
8959 {"object-lookups", no_argument, NULL, 'O'},
8960 {"path", required_argument, NULL, 'p'},
8961 {"parseable", no_argument, NULL, 'P'},
8962 {"skip-label", no_argument, NULL, 'q'},
8963 {"copy-object", no_argument, NULL, 'r'},
8964 {"read-block", no_argument, NULL, 'R'},
8965 {"io-stats", no_argument, NULL, 's'},
8966 {"simulate-dedup", no_argument, NULL, 'S'},
8967 {"txg", required_argument, NULL, 't'},
8968 {"brt-stats", no_argument, NULL, 'T'},
8969 {"uberblock", no_argument, NULL, 'u'},
8970 {"cachefile", required_argument, NULL, 'U'},
8971 {"verbose", no_argument, NULL, 'v'},
8972 {"verbatim", no_argument, NULL, 'V'},
8973 {"dump-blocks", required_argument, NULL, 'x'},
8974 {"extreme-rewind", no_argument, NULL, 'X'},
8975 {"all-reconstruction", no_argument, NULL, 'Y'},
8976 {"livelist", no_argument, NULL, 'y'},
8977 {"zstd-headers", no_argument, NULL, 'Z'},
8978 {0, 0, 0, 0}
8981 while ((c = getopt_long(argc, argv,
8982 "AbBcCdDeEFGhiI:kK:lLmMNo:Op:PqrRsSt:TuU:vVx:XYyZ",
8983 long_options, NULL)) != -1) {
8984 switch (c) {
8985 case 'b':
8986 case 'B':
8987 case 'c':
8988 case 'C':
8989 case 'd':
8990 case 'D':
8991 case 'E':
8992 case 'G':
8993 case 'h':
8994 case 'i':
8995 case 'l':
8996 case 'm':
8997 case 'M':
8998 case 'N':
8999 case 'O':
9000 case 'r':
9001 case 'R':
9002 case 's':
9003 case 'S':
9004 case 'T':
9005 case 'u':
9006 case 'y':
9007 case 'Z':
9008 dump_opt[c]++;
9009 dump_all = 0;
9010 break;
9011 case 'A':
9012 case 'e':
9013 case 'F':
9014 case 'k':
9015 case 'L':
9016 case 'P':
9017 case 'q':
9018 case 'X':
9019 dump_opt[c]++;
9020 break;
9021 case 'Y':
9022 zfs_reconstruct_indirect_combinations_max = INT_MAX;
9023 zfs_deadman_enabled = 0;
9024 break;
9025 /* NB: Sort single match options below. */
9026 case 'I':
9027 max_inflight_bytes = strtoull(optarg, NULL, 0);
9028 if (max_inflight_bytes == 0) {
9029 (void) fprintf(stderr, "maximum number "
9030 "of inflight bytes must be greater "
9031 "than 0\n");
9032 usage();
9034 break;
9035 case 'K':
9036 dump_opt[c]++;
9037 key_material = strdup(optarg);
9038 /* redact key material in process table */
9039 while (*optarg != '\0') { *optarg++ = '*'; }
9040 break;
9041 case 'o':
9042 error = set_global_var(optarg);
9043 if (error != 0)
9044 usage();
9045 break;
9046 case 'p':
9047 if (searchdirs == NULL) {
9048 searchdirs = umem_alloc(sizeof (char *),
9049 UMEM_NOFAIL);
9050 } else {
9051 char **tmp = umem_alloc((nsearch + 1) *
9052 sizeof (char *), UMEM_NOFAIL);
9053 memcpy(tmp, searchdirs, nsearch *
9054 sizeof (char *));
9055 umem_free(searchdirs,
9056 nsearch * sizeof (char *));
9057 searchdirs = tmp;
9059 searchdirs[nsearch++] = optarg;
9060 break;
9061 case 't':
9062 max_txg = strtoull(optarg, NULL, 0);
9063 if (max_txg < TXG_INITIAL) {
9064 (void) fprintf(stderr, "incorrect txg "
9065 "specified: %s\n", optarg);
9066 usage();
9068 break;
9069 case 'U':
9070 spa_config_path = optarg;
9071 if (spa_config_path[0] != '/') {
9072 (void) fprintf(stderr,
9073 "cachefile must be an absolute path "
9074 "(i.e. start with a slash)\n");
9075 usage();
9077 break;
9078 case 'v':
9079 verbose++;
9080 break;
9081 case 'V':
9082 flags = ZFS_IMPORT_VERBATIM;
9083 break;
9084 case 'x':
9085 vn_dumpdir = optarg;
9086 break;
9087 default:
9088 usage();
9089 break;
9093 if (!dump_opt['e'] && searchdirs != NULL) {
9094 (void) fprintf(stderr, "-p option requires use of -e\n");
9095 usage();
9097 #if defined(_LP64)
9099 * ZDB does not typically re-read blocks; therefore limit the ARC
9100 * to 256 MB, which can be used entirely for metadata.
9102 zfs_arc_min = 2ULL << SPA_MAXBLOCKSHIFT;
9103 zfs_arc_max = 256 * 1024 * 1024;
9104 #endif
9107 * "zdb -c" uses checksum-verifying scrub i/os which are async reads.
9108 * "zdb -b" uses traversal prefetch which uses async reads.
9109 * For good performance, let several of them be active at once.
9111 zfs_vdev_async_read_max_active = 10;
9114 * Disable reference tracking for better performance.
9116 reference_tracking_enable = B_FALSE;
9119 * Do not fail spa_load when spa_load_verify fails. This is needed
9120 * to load non-idle pools.
9122 spa_load_verify_dryrun = B_TRUE;
9125 * ZDB should have ability to read spacemaps.
9127 spa_mode_readable_spacemaps = B_TRUE;
9129 kernel_init(SPA_MODE_READ);
9131 if (dump_all)
9132 verbose = MAX(verbose, 1);
9134 for (c = 0; c < 256; c++) {
9135 if (dump_all && strchr("ABeEFkKlLNOPrRSXy", c) == NULL)
9136 dump_opt[c] = 1;
9137 if (dump_opt[c])
9138 dump_opt[c] += verbose;
9141 libspl_set_assert_ok((dump_opt['A'] == 1) || (dump_opt['A'] > 2));
9142 zfs_recover = (dump_opt['A'] > 1);
9144 argc -= optind;
9145 argv += optind;
9146 if (argc < 2 && dump_opt['R'])
9147 usage();
9149 if (dump_opt['E']) {
9150 if (argc != 1)
9151 usage();
9152 zdb_embedded_block(argv[0]);
9153 return (0);
9156 if (argc < 1) {
9157 if (!dump_opt['e'] && dump_opt['C']) {
9158 dump_cachefile(spa_config_path);
9159 return (0);
9161 usage();
9164 if (dump_opt['l'])
9165 return (dump_label(argv[0]));
9167 if (dump_opt['X'] || dump_opt['F'])
9168 rewind = ZPOOL_DO_REWIND |
9169 (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
9171 /* -N implies -d */
9172 if (dump_opt['N'] && dump_opt['d'] == 0)
9173 dump_opt['d'] = dump_opt['N'];
9175 if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
9176 nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, max_txg) != 0 ||
9177 nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY, rewind) != 0)
9178 fatal("internal error: %s", strerror(ENOMEM));
9180 error = 0;
9181 target = argv[0];
9183 if (strpbrk(target, "/@") != NULL) {
9184 size_t targetlen;
9186 target_pool = strdup(target);
9187 *strpbrk(target_pool, "/@") = '\0';
9189 target_is_spa = B_FALSE;
9190 targetlen = strlen(target);
9191 if (targetlen && target[targetlen - 1] == '/')
9192 target[targetlen - 1] = '\0';
9195 * See if an objset ID was supplied (-d <pool>/<objset ID>).
9196 * To disambiguate tank/100, consider the 100 as objsetID
9197 * if -N was given, otherwise 100 is an objsetID iff
9198 * tank/100 as a named dataset fails on lookup.
9200 objset_str = strchr(target, '/');
9201 if (objset_str && strlen(objset_str) > 1 &&
9202 zdb_numeric(objset_str + 1)) {
9203 char *endptr;
9204 errno = 0;
9205 objset_str++;
9206 objset_id = strtoull(objset_str, &endptr, 0);
9207 /* dataset 0 is the same as opening the pool */
9208 if (errno == 0 && endptr != objset_str &&
9209 objset_id != 0) {
9210 if (dump_opt['N'])
9211 dataset_lookup = B_TRUE;
9213 /* normal dataset name not an objset ID */
9214 if (endptr == objset_str) {
9215 objset_id = -1;
9217 } else if (objset_str && !zdb_numeric(objset_str + 1) &&
9218 dump_opt['N']) {
9219 printf("Supply a numeric objset ID with -N\n");
9220 exit(1);
9222 } else {
9223 target_pool = target;
9226 if (dump_opt['e']) {
9227 importargs_t args = { 0 };
9229 args.paths = nsearch;
9230 args.path = searchdirs;
9231 args.can_be_active = B_TRUE;
9233 libpc_handle_t lpch = {
9234 .lpc_lib_handle = NULL,
9235 .lpc_ops = &libzpool_config_ops,
9236 .lpc_printerr = B_TRUE
9238 error = zpool_find_config(&lpch, target_pool, &cfg, &args);
9240 if (error == 0) {
9242 if (nvlist_add_nvlist(cfg,
9243 ZPOOL_LOAD_POLICY, policy) != 0) {
9244 fatal("can't open '%s': %s",
9245 target, strerror(ENOMEM));
9248 if (dump_opt['C'] > 1) {
9249 (void) printf("\nConfiguration for import:\n");
9250 dump_nvlist(cfg, 8);
9254 * Disable the activity check to allow examination of
9255 * active pools.
9257 error = spa_import(target_pool, cfg, NULL,
9258 flags | ZFS_IMPORT_SKIP_MMP);
9262 if (searchdirs != NULL) {
9263 umem_free(searchdirs, nsearch * sizeof (char *));
9264 searchdirs = NULL;
9268 * We need to make sure to process -O option or call
9269 * dump_path after the -e option has been processed,
9270 * which imports the pool to the namespace if it's
9271 * not in the cachefile.
9273 if (dump_opt['O']) {
9274 if (argc != 2)
9275 usage();
9276 dump_opt['v'] = verbose + 3;
9277 return (dump_path(argv[0], argv[1], NULL));
9280 if (dump_opt['r']) {
9281 target_is_spa = B_FALSE;
9282 if (argc != 3)
9283 usage();
9284 dump_opt['v'] = verbose;
9285 error = dump_path(argv[0], argv[1], &object);
9286 if (error != 0)
9287 fatal("internal error: %s", strerror(error));
9291 * import_checkpointed_state makes the assumption that the
9292 * target pool that we pass it is already part of the spa
9293 * namespace. Because of that we need to make sure to call
9294 * it always after the -e option has been processed, which
9295 * imports the pool to the namespace if it's not in the
9296 * cachefile.
9298 char *checkpoint_pool = NULL;
9299 char *checkpoint_target = NULL;
9300 if (dump_opt['k']) {
9301 checkpoint_pool = import_checkpointed_state(target, cfg,
9302 &checkpoint_target);
9304 if (checkpoint_target != NULL)
9305 target = checkpoint_target;
9308 if (cfg != NULL) {
9309 nvlist_free(cfg);
9310 cfg = NULL;
9313 if (target_pool != target)
9314 free(target_pool);
9316 if (error == 0) {
9317 if (dump_opt['k'] && (target_is_spa || dump_opt['R'])) {
9318 ASSERT(checkpoint_pool != NULL);
9319 ASSERT(checkpoint_target == NULL);
9321 error = spa_open(checkpoint_pool, &spa, FTAG);
9322 if (error != 0) {
9323 fatal("Tried to open pool \"%s\" but "
9324 "spa_open() failed with error %d\n",
9325 checkpoint_pool, error);
9328 } else if (target_is_spa || dump_opt['R'] || dump_opt['B'] ||
9329 objset_id == 0) {
9330 zdb_set_skip_mmp(target);
9331 error = spa_open_rewind(target, &spa, FTAG, policy,
9332 NULL);
9333 if (error) {
9335 * If we're missing the log device then
9336 * try opening the pool after clearing the
9337 * log state.
9339 mutex_enter(&spa_namespace_lock);
9340 if ((spa = spa_lookup(target)) != NULL &&
9341 spa->spa_log_state == SPA_LOG_MISSING) {
9342 spa->spa_log_state = SPA_LOG_CLEAR;
9343 error = 0;
9345 mutex_exit(&spa_namespace_lock);
9347 if (!error) {
9348 error = spa_open_rewind(target, &spa,
9349 FTAG, policy, NULL);
9352 } else if (strpbrk(target, "#") != NULL) {
9353 dsl_pool_t *dp;
9354 error = dsl_pool_hold(target, FTAG, &dp);
9355 if (error != 0) {
9356 fatal("can't dump '%s': %s", target,
9357 strerror(error));
9359 error = dump_bookmark(dp, target, B_TRUE, verbose > 1);
9360 dsl_pool_rele(dp, FTAG);
9361 if (error != 0) {
9362 fatal("can't dump '%s': %s", target,
9363 strerror(error));
9365 return (error);
9366 } else {
9367 target_pool = strdup(target);
9368 if (strpbrk(target, "/@") != NULL)
9369 *strpbrk(target_pool, "/@") = '\0';
9371 zdb_set_skip_mmp(target);
9373 * If -N was supplied, the user has indicated that
9374 * zdb -d <pool>/<objsetID> is in effect. Otherwise
9375 * we first assume that the dataset string is the
9376 * dataset name. If dmu_objset_hold fails with the
9377 * dataset string, and we have an objset_id, retry the
9378 * lookup with the objsetID.
9380 boolean_t retry = B_TRUE;
9381 retry_lookup:
9382 if (dataset_lookup == B_TRUE) {
9384 * Use the supplied id to get the name
9385 * for open_objset.
9387 error = spa_open(target_pool, &spa, FTAG);
9388 if (error == 0) {
9389 error = name_from_objset_id(spa,
9390 objset_id, dsname);
9391 spa_close(spa, FTAG);
9392 if (error == 0)
9393 target = dsname;
9396 if (error == 0) {
9397 if (objset_id > 0 && retry) {
9398 int err = dmu_objset_hold(target, FTAG,
9399 &os);
9400 if (err) {
9401 dataset_lookup = B_TRUE;
9402 retry = B_FALSE;
9403 goto retry_lookup;
9404 } else {
9405 dmu_objset_rele(os, FTAG);
9408 error = open_objset(target, FTAG, &os);
9410 if (error == 0)
9411 spa = dmu_objset_spa(os);
9412 free(target_pool);
9415 nvlist_free(policy);
9417 if (error)
9418 fatal("can't open '%s': %s", target, strerror(error));
9421 * Set the pool failure mode to panic in order to prevent the pool
9422 * from suspending. A suspended I/O will have no way to resume and
9423 * can prevent the zdb(8) command from terminating as expected.
9425 if (spa != NULL)
9426 spa->spa_failmode = ZIO_FAILURE_MODE_PANIC;
9428 argv++;
9429 argc--;
9430 if (dump_opt['r']) {
9431 error = zdb_copy_object(os, object, argv[1]);
9432 } else if (!dump_opt['R']) {
9433 flagbits['d'] = ZOR_FLAG_DIRECTORY;
9434 flagbits['f'] = ZOR_FLAG_PLAIN_FILE;
9435 flagbits['m'] = ZOR_FLAG_SPACE_MAP;
9436 flagbits['z'] = ZOR_FLAG_ZAP;
9437 flagbits['A'] = ZOR_FLAG_ALL_TYPES;
9439 if (argc > 0 && dump_opt['d']) {
9440 zopt_object_args = argc;
9441 zopt_object_ranges = calloc(zopt_object_args,
9442 sizeof (zopt_object_range_t));
9443 for (unsigned i = 0; i < zopt_object_args; i++) {
9444 int err;
9445 const char *msg = NULL;
9447 err = parse_object_range(argv[i],
9448 &zopt_object_ranges[i], &msg);
9449 if (err != 0)
9450 fatal("Bad object or range: '%s': %s\n",
9451 argv[i], msg ?: "");
9453 } else if (argc > 0 && dump_opt['m']) {
9454 zopt_metaslab_args = argc;
9455 zopt_metaslab = calloc(zopt_metaslab_args,
9456 sizeof (uint64_t));
9457 for (unsigned i = 0; i < zopt_metaslab_args; i++) {
9458 errno = 0;
9459 zopt_metaslab[i] = strtoull(argv[i], NULL, 0);
9460 if (zopt_metaslab[i] == 0 && errno != 0)
9461 fatal("bad number %s: %s", argv[i],
9462 strerror(errno));
9465 if (dump_opt['B']) {
9466 dump_backup(target, objset_id,
9467 argc > 0 ? argv[0] : NULL);
9468 } else if (os != NULL) {
9469 dump_objset(os);
9470 } else if (zopt_object_args > 0 && !dump_opt['m']) {
9471 dump_objset(spa->spa_meta_objset);
9472 } else {
9473 dump_zpool(spa);
9475 } else {
9476 flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
9477 flagbits['c'] = ZDB_FLAG_CHECKSUM;
9478 flagbits['d'] = ZDB_FLAG_DECOMPRESS;
9479 flagbits['e'] = ZDB_FLAG_BSWAP;
9480 flagbits['g'] = ZDB_FLAG_GBH;
9481 flagbits['i'] = ZDB_FLAG_INDIRECT;
9482 flagbits['r'] = ZDB_FLAG_RAW;
9483 flagbits['v'] = ZDB_FLAG_VERBOSE;
9485 for (int i = 0; i < argc; i++)
9486 zdb_read_block(argv[i], spa);
9489 if (dump_opt['k']) {
9490 free(checkpoint_pool);
9491 if (!target_is_spa)
9492 free(checkpoint_target);
9495 if (os != NULL) {
9496 close_objset(os, FTAG);
9497 } else {
9498 spa_close(spa, FTAG);
9501 fuid_table_destroy();
9503 dump_debug_buffer();
9505 kernel_fini();
9507 return (error);