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