]> git.proxmox.com Git - mirror_zfs.git/blob - cmd/zdb/zdb.c
More adaptive ARC eviction
[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 uint_t zfs_vdev_async_read_max_active;
121 extern boolean_t spa_load_verify_dryrun;
122 extern boolean_t spa_mode_readable_spacemaps;
123 extern uint_t zfs_reconstruct_indirect_combinations_max;
124 extern uint_t zfs_btree_verify_intensity;
125
126 static const char cmdname[] = "zdb";
127 uint8_t dump_opt[256];
128
129 typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
130
131 static uint64_t *zopt_metaslab = NULL;
132 static unsigned zopt_metaslab_args = 0;
133
134 typedef struct zopt_object_range {
135 uint64_t zor_obj_start;
136 uint64_t zor_obj_end;
137 uint64_t zor_flags;
138 } zopt_object_range_t;
139
140 static zopt_object_range_t *zopt_object_ranges = NULL;
141 static unsigned zopt_object_args = 0;
142
143 static int flagbits[256];
144
145 #define ZOR_FLAG_PLAIN_FILE 0x0001
146 #define ZOR_FLAG_DIRECTORY 0x0002
147 #define ZOR_FLAG_SPACE_MAP 0x0004
148 #define ZOR_FLAG_ZAP 0x0008
149 #define ZOR_FLAG_ALL_TYPES -1
150 #define ZOR_SUPPORTED_FLAGS (ZOR_FLAG_PLAIN_FILE | \
151 ZOR_FLAG_DIRECTORY | \
152 ZOR_FLAG_SPACE_MAP | \
153 ZOR_FLAG_ZAP)
154
155 #define ZDB_FLAG_CHECKSUM 0x0001
156 #define ZDB_FLAG_DECOMPRESS 0x0002
157 #define ZDB_FLAG_BSWAP 0x0004
158 #define ZDB_FLAG_GBH 0x0008
159 #define ZDB_FLAG_INDIRECT 0x0010
160 #define ZDB_FLAG_RAW 0x0020
161 #define ZDB_FLAG_PRINT_BLKPTR 0x0040
162 #define ZDB_FLAG_VERBOSE 0x0080
163
164 static uint64_t max_inflight_bytes = 256 * 1024 * 1024; /* 256MB */
165 static int leaked_objects = 0;
166 static range_tree_t *mos_refd_objs;
167
168 static void snprintf_blkptr_compact(char *, size_t, const blkptr_t *,
169 boolean_t);
170 static void mos_obj_refd(uint64_t);
171 static void mos_obj_refd_multiple(uint64_t);
172 static int dump_bpobj_cb(void *arg, const blkptr_t *bp, boolean_t free,
173 dmu_tx_t *tx);
174
175 typedef struct sublivelist_verify {
176 /* FREE's that haven't yet matched to an ALLOC, in one sub-livelist */
177 zfs_btree_t sv_pair;
178
179 /* ALLOC's without a matching FREE, accumulates across sub-livelists */
180 zfs_btree_t sv_leftover;
181 } sublivelist_verify_t;
182
183 static int
184 livelist_compare(const void *larg, const void *rarg)
185 {
186 const blkptr_t *l = larg;
187 const blkptr_t *r = rarg;
188
189 /* Sort them according to dva[0] */
190 uint64_t l_dva0_vdev, r_dva0_vdev;
191 l_dva0_vdev = DVA_GET_VDEV(&l->blk_dva[0]);
192 r_dva0_vdev = DVA_GET_VDEV(&r->blk_dva[0]);
193 if (l_dva0_vdev < r_dva0_vdev)
194 return (-1);
195 else if (l_dva0_vdev > r_dva0_vdev)
196 return (+1);
197
198 /* if vdevs are equal, sort by offsets. */
199 uint64_t l_dva0_offset;
200 uint64_t r_dva0_offset;
201 l_dva0_offset = DVA_GET_OFFSET(&l->blk_dva[0]);
202 r_dva0_offset = DVA_GET_OFFSET(&r->blk_dva[0]);
203 if (l_dva0_offset < r_dva0_offset) {
204 return (-1);
205 } else if (l_dva0_offset > r_dva0_offset) {
206 return (+1);
207 }
208
209 /*
210 * Since we're storing blkptrs without cancelling FREE/ALLOC pairs,
211 * it's possible the offsets are equal. In that case, sort by txg
212 */
213 if (l->blk_birth < r->blk_birth) {
214 return (-1);
215 } else if (l->blk_birth > r->blk_birth) {
216 return (+1);
217 }
218 return (0);
219 }
220
221 typedef struct sublivelist_verify_block {
222 dva_t svb_dva;
223
224 /*
225 * We need this to check if the block marked as allocated
226 * in the livelist was freed (and potentially reallocated)
227 * in the metaslab spacemaps at a later TXG.
228 */
229 uint64_t svb_allocated_txg;
230 } sublivelist_verify_block_t;
231
232 static void zdb_print_blkptr(const blkptr_t *bp, int flags);
233
234 typedef struct sublivelist_verify_block_refcnt {
235 /* block pointer entry in livelist being verified */
236 blkptr_t svbr_blk;
237
238 /*
239 * Refcount gets incremented to 1 when we encounter the first
240 * FREE entry for the svfbr block pointer and a node for it
241 * is created in our ZDB verification/tracking metadata.
242 *
243 * As we encounter more FREE entries we increment this counter
244 * and similarly decrement it whenever we find the respective
245 * ALLOC entries for this block.
246 *
247 * When the refcount gets to 0 it means that all the FREE and
248 * ALLOC entries of this block have paired up and we no longer
249 * need to track it in our verification logic (e.g. the node
250 * containing this struct in our verification data structure
251 * should be freed).
252 *
253 * [refer to sublivelist_verify_blkptr() for the actual code]
254 */
255 uint32_t svbr_refcnt;
256 } sublivelist_verify_block_refcnt_t;
257
258 static int
259 sublivelist_block_refcnt_compare(const void *larg, const void *rarg)
260 {
261 const sublivelist_verify_block_refcnt_t *l = larg;
262 const sublivelist_verify_block_refcnt_t *r = rarg;
263 return (livelist_compare(&l->svbr_blk, &r->svbr_blk));
264 }
265
266 static int
267 sublivelist_verify_blkptr(void *arg, const blkptr_t *bp, boolean_t free,
268 dmu_tx_t *tx)
269 {
270 ASSERT3P(tx, ==, NULL);
271 struct sublivelist_verify *sv = arg;
272 sublivelist_verify_block_refcnt_t current = {
273 .svbr_blk = *bp,
274
275 /*
276 * Start with 1 in case this is the first free entry.
277 * This field is not used for our B-Tree comparisons
278 * anyway.
279 */
280 .svbr_refcnt = 1,
281 };
282
283 zfs_btree_index_t where;
284 sublivelist_verify_block_refcnt_t *pair =
285 zfs_btree_find(&sv->sv_pair, &current, &where);
286 if (free) {
287 if (pair == NULL) {
288 /* first free entry for this block pointer */
289 zfs_btree_add(&sv->sv_pair, &current);
290 } else {
291 pair->svbr_refcnt++;
292 }
293 } else {
294 if (pair == NULL) {
295 /* block that is currently marked as allocated */
296 for (int i = 0; i < SPA_DVAS_PER_BP; i++) {
297 if (DVA_IS_EMPTY(&bp->blk_dva[i]))
298 break;
299 sublivelist_verify_block_t svb = {
300 .svb_dva = bp->blk_dva[i],
301 .svb_allocated_txg = bp->blk_birth
302 };
303
304 if (zfs_btree_find(&sv->sv_leftover, &svb,
305 &where) == NULL) {
306 zfs_btree_add_idx(&sv->sv_leftover,
307 &svb, &where);
308 }
309 }
310 } else {
311 /* alloc matches a free entry */
312 pair->svbr_refcnt--;
313 if (pair->svbr_refcnt == 0) {
314 /* all allocs and frees have been matched */
315 zfs_btree_remove_idx(&sv->sv_pair, &where);
316 }
317 }
318 }
319
320 return (0);
321 }
322
323 static int
324 sublivelist_verify_func(void *args, dsl_deadlist_entry_t *dle)
325 {
326 int err;
327 struct sublivelist_verify *sv = args;
328
329 zfs_btree_create(&sv->sv_pair, sublivelist_block_refcnt_compare,
330 sizeof (sublivelist_verify_block_refcnt_t));
331
332 err = bpobj_iterate_nofree(&dle->dle_bpobj, sublivelist_verify_blkptr,
333 sv, NULL);
334
335 sublivelist_verify_block_refcnt_t *e;
336 zfs_btree_index_t *cookie = NULL;
337 while ((e = zfs_btree_destroy_nodes(&sv->sv_pair, &cookie)) != NULL) {
338 char blkbuf[BP_SPRINTF_LEN];
339 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf),
340 &e->svbr_blk, B_TRUE);
341 (void) printf("\tERROR: %d unmatched FREE(s): %s\n",
342 e->svbr_refcnt, blkbuf);
343 }
344 zfs_btree_destroy(&sv->sv_pair);
345
346 return (err);
347 }
348
349 static int
350 livelist_block_compare(const void *larg, const void *rarg)
351 {
352 const sublivelist_verify_block_t *l = larg;
353 const sublivelist_verify_block_t *r = rarg;
354
355 if (DVA_GET_VDEV(&l->svb_dva) < DVA_GET_VDEV(&r->svb_dva))
356 return (-1);
357 else if (DVA_GET_VDEV(&l->svb_dva) > DVA_GET_VDEV(&r->svb_dva))
358 return (+1);
359
360 if (DVA_GET_OFFSET(&l->svb_dva) < DVA_GET_OFFSET(&r->svb_dva))
361 return (-1);
362 else if (DVA_GET_OFFSET(&l->svb_dva) > DVA_GET_OFFSET(&r->svb_dva))
363 return (+1);
364
365 if (DVA_GET_ASIZE(&l->svb_dva) < DVA_GET_ASIZE(&r->svb_dva))
366 return (-1);
367 else if (DVA_GET_ASIZE(&l->svb_dva) > DVA_GET_ASIZE(&r->svb_dva))
368 return (+1);
369
370 return (0);
371 }
372
373 /*
374 * Check for errors in a livelist while tracking all unfreed ALLOCs in the
375 * sublivelist_verify_t: sv->sv_leftover
376 */
377 static void
378 livelist_verify(dsl_deadlist_t *dl, void *arg)
379 {
380 sublivelist_verify_t *sv = arg;
381 dsl_deadlist_iterate(dl, sublivelist_verify_func, sv);
382 }
383
384 /*
385 * Check for errors in the livelist entry and discard the intermediary
386 * data structures
387 */
388 static int
389 sublivelist_verify_lightweight(void *args, dsl_deadlist_entry_t *dle)
390 {
391 (void) args;
392 sublivelist_verify_t sv;
393 zfs_btree_create(&sv.sv_leftover, livelist_block_compare,
394 sizeof (sublivelist_verify_block_t));
395 int err = sublivelist_verify_func(&sv, dle);
396 zfs_btree_clear(&sv.sv_leftover);
397 zfs_btree_destroy(&sv.sv_leftover);
398 return (err);
399 }
400
401 typedef struct metaslab_verify {
402 /*
403 * Tree containing all the leftover ALLOCs from the livelists
404 * that are part of this metaslab.
405 */
406 zfs_btree_t mv_livelist_allocs;
407
408 /*
409 * Metaslab information.
410 */
411 uint64_t mv_vdid;
412 uint64_t mv_msid;
413 uint64_t mv_start;
414 uint64_t mv_end;
415
416 /*
417 * What's currently allocated for this metaslab.
418 */
419 range_tree_t *mv_allocated;
420 } metaslab_verify_t;
421
422 typedef void ll_iter_t(dsl_deadlist_t *ll, void *arg);
423
424 typedef int (*zdb_log_sm_cb_t)(spa_t *spa, space_map_entry_t *sme, uint64_t txg,
425 void *arg);
426
427 typedef struct unflushed_iter_cb_arg {
428 spa_t *uic_spa;
429 uint64_t uic_txg;
430 void *uic_arg;
431 zdb_log_sm_cb_t uic_cb;
432 } unflushed_iter_cb_arg_t;
433
434 static int
435 iterate_through_spacemap_logs_cb(space_map_entry_t *sme, void *arg)
436 {
437 unflushed_iter_cb_arg_t *uic = arg;
438 return (uic->uic_cb(uic->uic_spa, sme, uic->uic_txg, uic->uic_arg));
439 }
440
441 static void
442 iterate_through_spacemap_logs(spa_t *spa, zdb_log_sm_cb_t cb, void *arg)
443 {
444 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
445 return;
446
447 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
448 for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
449 sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls)) {
450 space_map_t *sm = NULL;
451 VERIFY0(space_map_open(&sm, spa_meta_objset(spa),
452 sls->sls_sm_obj, 0, UINT64_MAX, SPA_MINBLOCKSHIFT));
453
454 unflushed_iter_cb_arg_t uic = {
455 .uic_spa = spa,
456 .uic_txg = sls->sls_txg,
457 .uic_arg = arg,
458 .uic_cb = cb
459 };
460 VERIFY0(space_map_iterate(sm, space_map_length(sm),
461 iterate_through_spacemap_logs_cb, &uic));
462 space_map_close(sm);
463 }
464 spa_config_exit(spa, SCL_CONFIG, FTAG);
465 }
466
467 static void
468 verify_livelist_allocs(metaslab_verify_t *mv, uint64_t txg,
469 uint64_t offset, uint64_t size)
470 {
471 sublivelist_verify_block_t svb = {{{0}}};
472 DVA_SET_VDEV(&svb.svb_dva, mv->mv_vdid);
473 DVA_SET_OFFSET(&svb.svb_dva, offset);
474 DVA_SET_ASIZE(&svb.svb_dva, size);
475 zfs_btree_index_t where;
476 uint64_t end_offset = offset + size;
477
478 /*
479 * Look for an exact match for spacemap entry in the livelist entries.
480 * Then, look for other livelist entries that fall within the range
481 * of the spacemap entry as it may have been condensed
482 */
483 sublivelist_verify_block_t *found =
484 zfs_btree_find(&mv->mv_livelist_allocs, &svb, &where);
485 if (found == NULL) {
486 found = zfs_btree_next(&mv->mv_livelist_allocs, &where, &where);
487 }
488 for (; found != NULL && DVA_GET_VDEV(&found->svb_dva) == mv->mv_vdid &&
489 DVA_GET_OFFSET(&found->svb_dva) < end_offset;
490 found = zfs_btree_next(&mv->mv_livelist_allocs, &where, &where)) {
491 if (found->svb_allocated_txg <= txg) {
492 (void) printf("ERROR: Livelist ALLOC [%llx:%llx] "
493 "from TXG %llx FREED at TXG %llx\n",
494 (u_longlong_t)DVA_GET_OFFSET(&found->svb_dva),
495 (u_longlong_t)DVA_GET_ASIZE(&found->svb_dva),
496 (u_longlong_t)found->svb_allocated_txg,
497 (u_longlong_t)txg);
498 }
499 }
500 }
501
502 static int
503 metaslab_spacemap_validation_cb(space_map_entry_t *sme, void *arg)
504 {
505 metaslab_verify_t *mv = arg;
506 uint64_t offset = sme->sme_offset;
507 uint64_t size = sme->sme_run;
508 uint64_t txg = sme->sme_txg;
509
510 if (sme->sme_type == SM_ALLOC) {
511 if (range_tree_contains(mv->mv_allocated,
512 offset, size)) {
513 (void) printf("ERROR: DOUBLE ALLOC: "
514 "%llu [%llx:%llx] "
515 "%llu:%llu LOG_SM\n",
516 (u_longlong_t)txg, (u_longlong_t)offset,
517 (u_longlong_t)size, (u_longlong_t)mv->mv_vdid,
518 (u_longlong_t)mv->mv_msid);
519 } else {
520 range_tree_add(mv->mv_allocated,
521 offset, size);
522 }
523 } else {
524 if (!range_tree_contains(mv->mv_allocated,
525 offset, size)) {
526 (void) printf("ERROR: DOUBLE FREE: "
527 "%llu [%llx:%llx] "
528 "%llu:%llu LOG_SM\n",
529 (u_longlong_t)txg, (u_longlong_t)offset,
530 (u_longlong_t)size, (u_longlong_t)mv->mv_vdid,
531 (u_longlong_t)mv->mv_msid);
532 } else {
533 range_tree_remove(mv->mv_allocated,
534 offset, size);
535 }
536 }
537
538 if (sme->sme_type != SM_ALLOC) {
539 /*
540 * If something is freed in the spacemap, verify that
541 * it is not listed as allocated in the livelist.
542 */
543 verify_livelist_allocs(mv, txg, offset, size);
544 }
545 return (0);
546 }
547
548 static int
549 spacemap_check_sm_log_cb(spa_t *spa, space_map_entry_t *sme,
550 uint64_t txg, void *arg)
551 {
552 metaslab_verify_t *mv = arg;
553 uint64_t offset = sme->sme_offset;
554 uint64_t vdev_id = sme->sme_vdev;
555
556 vdev_t *vd = vdev_lookup_top(spa, vdev_id);
557
558 /* skip indirect vdevs */
559 if (!vdev_is_concrete(vd))
560 return (0);
561
562 if (vdev_id != mv->mv_vdid)
563 return (0);
564
565 metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
566 if (ms->ms_id != mv->mv_msid)
567 return (0);
568
569 if (txg < metaslab_unflushed_txg(ms))
570 return (0);
571
572
573 ASSERT3U(txg, ==, sme->sme_txg);
574 return (metaslab_spacemap_validation_cb(sme, mv));
575 }
576
577 static void
578 spacemap_check_sm_log(spa_t *spa, metaslab_verify_t *mv)
579 {
580 iterate_through_spacemap_logs(spa, spacemap_check_sm_log_cb, mv);
581 }
582
583 static void
584 spacemap_check_ms_sm(space_map_t *sm, metaslab_verify_t *mv)
585 {
586 if (sm == NULL)
587 return;
588
589 VERIFY0(space_map_iterate(sm, space_map_length(sm),
590 metaslab_spacemap_validation_cb, mv));
591 }
592
593 static void iterate_deleted_livelists(spa_t *spa, ll_iter_t func, void *arg);
594
595 /*
596 * Transfer blocks from sv_leftover tree to the mv_livelist_allocs if
597 * they are part of that metaslab (mv_msid).
598 */
599 static void
600 mv_populate_livelist_allocs(metaslab_verify_t *mv, sublivelist_verify_t *sv)
601 {
602 zfs_btree_index_t where;
603 sublivelist_verify_block_t *svb;
604 ASSERT3U(zfs_btree_numnodes(&mv->mv_livelist_allocs), ==, 0);
605 for (svb = zfs_btree_first(&sv->sv_leftover, &where);
606 svb != NULL;
607 svb = zfs_btree_next(&sv->sv_leftover, &where, &where)) {
608 if (DVA_GET_VDEV(&svb->svb_dva) != mv->mv_vdid)
609 continue;
610
611 if (DVA_GET_OFFSET(&svb->svb_dva) < mv->mv_start &&
612 (DVA_GET_OFFSET(&svb->svb_dva) +
613 DVA_GET_ASIZE(&svb->svb_dva)) > mv->mv_start) {
614 (void) printf("ERROR: Found block that crosses "
615 "metaslab boundary: <%llu:%llx:%llx>\n",
616 (u_longlong_t)DVA_GET_VDEV(&svb->svb_dva),
617 (u_longlong_t)DVA_GET_OFFSET(&svb->svb_dva),
618 (u_longlong_t)DVA_GET_ASIZE(&svb->svb_dva));
619 continue;
620 }
621
622 if (DVA_GET_OFFSET(&svb->svb_dva) < mv->mv_start)
623 continue;
624
625 if (DVA_GET_OFFSET(&svb->svb_dva) >= mv->mv_end)
626 continue;
627
628 if ((DVA_GET_OFFSET(&svb->svb_dva) +
629 DVA_GET_ASIZE(&svb->svb_dva)) > mv->mv_end) {
630 (void) printf("ERROR: Found block that crosses "
631 "metaslab boundary: <%llu:%llx:%llx>\n",
632 (u_longlong_t)DVA_GET_VDEV(&svb->svb_dva),
633 (u_longlong_t)DVA_GET_OFFSET(&svb->svb_dva),
634 (u_longlong_t)DVA_GET_ASIZE(&svb->svb_dva));
635 continue;
636 }
637
638 zfs_btree_add(&mv->mv_livelist_allocs, svb);
639 }
640
641 for (svb = zfs_btree_first(&mv->mv_livelist_allocs, &where);
642 svb != NULL;
643 svb = zfs_btree_next(&mv->mv_livelist_allocs, &where, &where)) {
644 zfs_btree_remove(&sv->sv_leftover, svb);
645 }
646 }
647
648 /*
649 * [Livelist Check]
650 * Iterate through all the sublivelists and:
651 * - report leftover frees (**)
652 * - record leftover ALLOCs together with their TXG [see Cross Check]
653 *
654 * (**) Note: Double ALLOCs are valid in datasets that have dedup
655 * enabled. Similarly double FREEs are allowed as well but
656 * only if they pair up with a corresponding ALLOC entry once
657 * we our done with our sublivelist iteration.
658 *
659 * [Spacemap Check]
660 * for each metaslab:
661 * - iterate over spacemap and then the metaslab's entries in the
662 * spacemap log, then report any double FREEs and ALLOCs (do not
663 * blow up).
664 *
665 * [Cross Check]
666 * After finishing the Livelist Check phase and while being in the
667 * Spacemap Check phase, we find all the recorded leftover ALLOCs
668 * of the livelist check that are part of the metaslab that we are
669 * currently looking at in the Spacemap Check. We report any entries
670 * that are marked as ALLOCs in the livelists but have been actually
671 * freed (and potentially allocated again) after their TXG stamp in
672 * the spacemaps. Also report any ALLOCs from the livelists that
673 * belong to indirect vdevs (e.g. their vdev completed removal).
674 *
675 * Note that this will miss Log Spacemap entries that cancelled each other
676 * out before being flushed to the metaslab, so we are not guaranteed
677 * to match all erroneous ALLOCs.
678 */
679 static void
680 livelist_metaslab_validate(spa_t *spa)
681 {
682 (void) printf("Verifying deleted livelist entries\n");
683
684 sublivelist_verify_t sv;
685 zfs_btree_create(&sv.sv_leftover, livelist_block_compare,
686 sizeof (sublivelist_verify_block_t));
687 iterate_deleted_livelists(spa, livelist_verify, &sv);
688
689 (void) printf("Verifying metaslab entries\n");
690 vdev_t *rvd = spa->spa_root_vdev;
691 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
692 vdev_t *vd = rvd->vdev_child[c];
693
694 if (!vdev_is_concrete(vd))
695 continue;
696
697 for (uint64_t mid = 0; mid < vd->vdev_ms_count; mid++) {
698 metaslab_t *m = vd->vdev_ms[mid];
699
700 (void) fprintf(stderr,
701 "\rverifying concrete vdev %llu, "
702 "metaslab %llu of %llu ...",
703 (longlong_t)vd->vdev_id,
704 (longlong_t)mid,
705 (longlong_t)vd->vdev_ms_count);
706
707 uint64_t shift, start;
708 range_seg_type_t type =
709 metaslab_calculate_range_tree_type(vd, m,
710 &start, &shift);
711 metaslab_verify_t mv;
712 mv.mv_allocated = range_tree_create(NULL,
713 type, NULL, start, shift);
714 mv.mv_vdid = vd->vdev_id;
715 mv.mv_msid = m->ms_id;
716 mv.mv_start = m->ms_start;
717 mv.mv_end = m->ms_start + m->ms_size;
718 zfs_btree_create(&mv.mv_livelist_allocs,
719 livelist_block_compare,
720 sizeof (sublivelist_verify_block_t));
721
722 mv_populate_livelist_allocs(&mv, &sv);
723
724 spacemap_check_ms_sm(m->ms_sm, &mv);
725 spacemap_check_sm_log(spa, &mv);
726
727 range_tree_vacate(mv.mv_allocated, NULL, NULL);
728 range_tree_destroy(mv.mv_allocated);
729 zfs_btree_clear(&mv.mv_livelist_allocs);
730 zfs_btree_destroy(&mv.mv_livelist_allocs);
731 }
732 }
733 (void) fprintf(stderr, "\n");
734
735 /*
736 * If there are any segments in the leftover tree after we walked
737 * through all the metaslabs in the concrete vdevs then this means
738 * that we have segments in the livelists that belong to indirect
739 * vdevs and are marked as allocated.
740 */
741 if (zfs_btree_numnodes(&sv.sv_leftover) == 0) {
742 zfs_btree_destroy(&sv.sv_leftover);
743 return;
744 }
745 (void) printf("ERROR: Found livelist blocks marked as allocated "
746 "for indirect vdevs:\n");
747
748 zfs_btree_index_t *where = NULL;
749 sublivelist_verify_block_t *svb;
750 while ((svb = zfs_btree_destroy_nodes(&sv.sv_leftover, &where)) !=
751 NULL) {
752 int vdev_id = DVA_GET_VDEV(&svb->svb_dva);
753 ASSERT3U(vdev_id, <, rvd->vdev_children);
754 vdev_t *vd = rvd->vdev_child[vdev_id];
755 ASSERT(!vdev_is_concrete(vd));
756 (void) printf("<%d:%llx:%llx> TXG %llx\n",
757 vdev_id, (u_longlong_t)DVA_GET_OFFSET(&svb->svb_dva),
758 (u_longlong_t)DVA_GET_ASIZE(&svb->svb_dva),
759 (u_longlong_t)svb->svb_allocated_txg);
760 }
761 (void) printf("\n");
762 zfs_btree_destroy(&sv.sv_leftover);
763 }
764
765 /*
766 * These libumem hooks provide a reasonable set of defaults for the allocator's
767 * debugging facilities.
768 */
769 const char *
770 _umem_debug_init(void)
771 {
772 return ("default,verbose"); /* $UMEM_DEBUG setting */
773 }
774
775 const char *
776 _umem_logging_init(void)
777 {
778 return ("fail,contents"); /* $UMEM_LOGGING setting */
779 }
780
781 static void
782 usage(void)
783 {
784 (void) fprintf(stderr,
785 "Usage:\t%s [-AbcdDFGhikLMPsvXy] [-e [-V] [-p <path> ...]] "
786 "[-I <inflight I/Os>]\n"
787 "\t\t[-o <var>=<value>]... [-t <txg>] [-U <cache>] [-x <dumpdir>]\n"
788 "\t\t[-K <key>]\n"
789 "\t\t[<poolname>[/<dataset | objset id>] [<object | range> ...]]\n"
790 "\t%s [-AdiPv] [-e [-V] [-p <path> ...]] [-U <cache>] [-K <key>]\n"
791 "\t\t[<poolname>[/<dataset | objset id>] [<object | range> ...]\n"
792 "\t%s [-v] <bookmark>\n"
793 "\t%s -C [-A] [-U <cache>]\n"
794 "\t%s -l [-Aqu] <device>\n"
795 "\t%s -m [-AFLPX] [-e [-V] [-p <path> ...]] [-t <txg>] "
796 "[-U <cache>]\n\t\t<poolname> [<vdev> [<metaslab> ...]]\n"
797 "\t%s -O [-K <key>] <dataset> <path>\n"
798 "\t%s -r [-K <key>] <dataset> <path> <destination>\n"
799 "\t%s -R [-A] [-e [-V] [-p <path> ...]] [-U <cache>]\n"
800 "\t\t<poolname> <vdev>:<offset>:<size>[:<flags>]\n"
801 "\t%s -E [-A] word0:word1:...:word15\n"
802 "\t%s -S [-AP] [-e [-V] [-p <path> ...]] [-U <cache>] "
803 "<poolname>\n\n",
804 cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname,
805 cmdname, cmdname, cmdname, cmdname);
806
807 (void) fprintf(stderr, " Dataset name must include at least one "
808 "separator character '/' or '@'\n");
809 (void) fprintf(stderr, " If dataset name is specified, only that "
810 "dataset is dumped\n");
811 (void) fprintf(stderr, " If object numbers or object number "
812 "ranges are specified, only those\n"
813 " objects or ranges are dumped.\n\n");
814 (void) fprintf(stderr,
815 " Object ranges take the form <start>:<end>[:<flags>]\n"
816 " start Starting object number\n"
817 " end Ending object number, or -1 for no upper bound\n"
818 " flags Optional flags to select object types:\n"
819 " A All objects (this is the default)\n"
820 " d ZFS directories\n"
821 " f ZFS files \n"
822 " m SPA space maps\n"
823 " z ZAPs\n"
824 " - Negate effect of next flag\n\n");
825 (void) fprintf(stderr, " Options to control amount of output:\n");
826 (void) fprintf(stderr, " -b --block-stats "
827 "block statistics\n");
828 (void) fprintf(stderr, " -c --checksum "
829 "checksum all metadata (twice for all data) blocks\n");
830 (void) fprintf(stderr, " -C --config "
831 "config (or cachefile if alone)\n");
832 (void) fprintf(stderr, " -d --datasets "
833 "dataset(s)\n");
834 (void) fprintf(stderr, " -D --dedup-stats "
835 "dedup statistics\n");
836 (void) fprintf(stderr, " -E --embedded-block-pointer=INTEGER\n"
837 " decode and display block "
838 "from an embedded block pointer\n");
839 (void) fprintf(stderr, " -h --history "
840 "pool history\n");
841 (void) fprintf(stderr, " -i --intent-logs "
842 "intent logs\n");
843 (void) fprintf(stderr, " -l --label "
844 "read label contents\n");
845 (void) fprintf(stderr, " -k --checkpointed-state "
846 "examine the checkpointed state of the pool\n");
847 (void) fprintf(stderr, " -L --disable-leak-tracking "
848 "disable leak tracking (do not load spacemaps)\n");
849 (void) fprintf(stderr, " -m --metaslabs "
850 "metaslabs\n");
851 (void) fprintf(stderr, " -M --metaslab-groups "
852 "metaslab groups\n");
853 (void) fprintf(stderr, " -O --object-lookups "
854 "perform object lookups by path\n");
855 (void) fprintf(stderr, " -r --copy-object "
856 "copy an object by path to file\n");
857 (void) fprintf(stderr, " -R --read-block "
858 "read and display block from a device\n");
859 (void) fprintf(stderr, " -s --io-stats "
860 "report stats on zdb's I/O\n");
861 (void) fprintf(stderr, " -S --simulate-dedup "
862 "simulate dedup to measure effect\n");
863 (void) fprintf(stderr, " -v --verbose "
864 "verbose (applies to all others)\n");
865 (void) fprintf(stderr, " -y --livelist "
866 "perform livelist and metaslab validation on any livelists being "
867 "deleted\n\n");
868 (void) fprintf(stderr, " Below options are intended for use "
869 "with other options:\n");
870 (void) fprintf(stderr, " -A --ignore-assertions "
871 "ignore assertions (-A), enable panic recovery (-AA) or both "
872 "(-AAA)\n");
873 (void) fprintf(stderr, " -e --exported "
874 "pool is exported/destroyed/has altroot/not in a cachefile\n");
875 (void) fprintf(stderr, " -F --automatic-rewind "
876 "attempt automatic rewind within safe range of transaction "
877 "groups\n");
878 (void) fprintf(stderr, " -G --dump-debug-msg "
879 "dump zfs_dbgmsg buffer before exiting\n");
880 (void) fprintf(stderr, " -I --inflight=INTEGER "
881 "specify the maximum number of checksumming I/Os "
882 "[default is 200]\n");
883 (void) fprintf(stderr, " -K --key=KEY "
884 "decryption key for encrypted dataset\n");
885 (void) fprintf(stderr, " -o --option=\"OPTION=INTEGER\" "
886 "set global variable to an unsigned 32-bit integer\n");
887 (void) fprintf(stderr, " -p --path==PATH "
888 "use one or more with -e to specify path to vdev dir\n");
889 (void) fprintf(stderr, " -P --parseable "
890 "print numbers in parseable form\n");
891 (void) fprintf(stderr, " -q --skip-label "
892 "don't print label contents\n");
893 (void) fprintf(stderr, " -t --txg=INTEGER "
894 "highest txg to use when searching for uberblocks\n");
895 (void) fprintf(stderr, " -u --uberblock "
896 "uberblock\n");
897 (void) fprintf(stderr, " -U --cachefile=PATH "
898 "use alternate cachefile\n");
899 (void) fprintf(stderr, " -V --verbatim "
900 "do verbatim import\n");
901 (void) fprintf(stderr, " -x --dump-blocks=PATH "
902 "dump all read blocks into specified directory\n");
903 (void) fprintf(stderr, " -X --extreme-rewind "
904 "attempt extreme rewind (does not work with dataset)\n");
905 (void) fprintf(stderr, " -Y --all-reconstruction "
906 "attempt all reconstruction combinations for split blocks\n");
907 (void) fprintf(stderr, " -Z --zstd-headers "
908 "show ZSTD headers \n");
909 (void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
910 "to make only that option verbose\n");
911 (void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
912 exit(1);
913 }
914
915 static void
916 dump_debug_buffer(void)
917 {
918 if (dump_opt['G']) {
919 (void) printf("\n");
920 (void) fflush(stdout);
921 zfs_dbgmsg_print("zdb");
922 }
923 }
924
925 /*
926 * Called for usage errors that are discovered after a call to spa_open(),
927 * dmu_bonus_hold(), or pool_match(). abort() is called for other errors.
928 */
929
930 static void
931 fatal(const char *fmt, ...)
932 {
933 va_list ap;
934
935 va_start(ap, fmt);
936 (void) fprintf(stderr, "%s: ", cmdname);
937 (void) vfprintf(stderr, fmt, ap);
938 va_end(ap);
939 (void) fprintf(stderr, "\n");
940
941 dump_debug_buffer();
942
943 exit(1);
944 }
945
946 static void
947 dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
948 {
949 (void) size;
950 nvlist_t *nv;
951 size_t nvsize = *(uint64_t *)data;
952 char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
953
954 VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
955
956 VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
957
958 umem_free(packed, nvsize);
959
960 dump_nvlist(nv, 8);
961
962 nvlist_free(nv);
963 }
964
965 static void
966 dump_history_offsets(objset_t *os, uint64_t object, void *data, size_t size)
967 {
968 (void) os, (void) object, (void) size;
969 spa_history_phys_t *shp = data;
970
971 if (shp == NULL)
972 return;
973
974 (void) printf("\t\tpool_create_len = %llu\n",
975 (u_longlong_t)shp->sh_pool_create_len);
976 (void) printf("\t\tphys_max_off = %llu\n",
977 (u_longlong_t)shp->sh_phys_max_off);
978 (void) printf("\t\tbof = %llu\n",
979 (u_longlong_t)shp->sh_bof);
980 (void) printf("\t\teof = %llu\n",
981 (u_longlong_t)shp->sh_eof);
982 (void) printf("\t\trecords_lost = %llu\n",
983 (u_longlong_t)shp->sh_records_lost);
984 }
985
986 static void
987 zdb_nicenum(uint64_t num, char *buf, size_t buflen)
988 {
989 if (dump_opt['P'])
990 (void) snprintf(buf, buflen, "%llu", (longlong_t)num);
991 else
992 nicenum(num, buf, buflen);
993 }
994
995 static const char histo_stars[] = "****************************************";
996 static const uint64_t histo_width = sizeof (histo_stars) - 1;
997
998 static void
999 dump_histogram(const uint64_t *histo, int size, int offset)
1000 {
1001 int i;
1002 int minidx = size - 1;
1003 int maxidx = 0;
1004 uint64_t max = 0;
1005
1006 for (i = 0; i < size; i++) {
1007 if (histo[i] > max)
1008 max = histo[i];
1009 if (histo[i] > 0 && i > maxidx)
1010 maxidx = i;
1011 if (histo[i] > 0 && i < minidx)
1012 minidx = i;
1013 }
1014
1015 if (max < histo_width)
1016 max = histo_width;
1017
1018 for (i = minidx; i <= maxidx; i++) {
1019 (void) printf("\t\t\t%3u: %6llu %s\n",
1020 i + offset, (u_longlong_t)histo[i],
1021 &histo_stars[(max - histo[i]) * histo_width / max]);
1022 }
1023 }
1024
1025 static void
1026 dump_zap_stats(objset_t *os, uint64_t object)
1027 {
1028 int error;
1029 zap_stats_t zs;
1030
1031 error = zap_get_stats(os, object, &zs);
1032 if (error)
1033 return;
1034
1035 if (zs.zs_ptrtbl_len == 0) {
1036 ASSERT(zs.zs_num_blocks == 1);
1037 (void) printf("\tmicrozap: %llu bytes, %llu entries\n",
1038 (u_longlong_t)zs.zs_blocksize,
1039 (u_longlong_t)zs.zs_num_entries);
1040 return;
1041 }
1042
1043 (void) printf("\tFat ZAP stats:\n");
1044
1045 (void) printf("\t\tPointer table:\n");
1046 (void) printf("\t\t\t%llu elements\n",
1047 (u_longlong_t)zs.zs_ptrtbl_len);
1048 (void) printf("\t\t\tzt_blk: %llu\n",
1049 (u_longlong_t)zs.zs_ptrtbl_zt_blk);
1050 (void) printf("\t\t\tzt_numblks: %llu\n",
1051 (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
1052 (void) printf("\t\t\tzt_shift: %llu\n",
1053 (u_longlong_t)zs.zs_ptrtbl_zt_shift);
1054 (void) printf("\t\t\tzt_blks_copied: %llu\n",
1055 (u_longlong_t)zs.zs_ptrtbl_blks_copied);
1056 (void) printf("\t\t\tzt_nextblk: %llu\n",
1057 (u_longlong_t)zs.zs_ptrtbl_nextblk);
1058
1059 (void) printf("\t\tZAP entries: %llu\n",
1060 (u_longlong_t)zs.zs_num_entries);
1061 (void) printf("\t\tLeaf blocks: %llu\n",
1062 (u_longlong_t)zs.zs_num_leafs);
1063 (void) printf("\t\tTotal blocks: %llu\n",
1064 (u_longlong_t)zs.zs_num_blocks);
1065 (void) printf("\t\tzap_block_type: 0x%llx\n",
1066 (u_longlong_t)zs.zs_block_type);
1067 (void) printf("\t\tzap_magic: 0x%llx\n",
1068 (u_longlong_t)zs.zs_magic);
1069 (void) printf("\t\tzap_salt: 0x%llx\n",
1070 (u_longlong_t)zs.zs_salt);
1071
1072 (void) printf("\t\tLeafs with 2^n pointers:\n");
1073 dump_histogram(zs.zs_leafs_with_2n_pointers, ZAP_HISTOGRAM_SIZE, 0);
1074
1075 (void) printf("\t\tBlocks with n*5 entries:\n");
1076 dump_histogram(zs.zs_blocks_with_n5_entries, ZAP_HISTOGRAM_SIZE, 0);
1077
1078 (void) printf("\t\tBlocks n/10 full:\n");
1079 dump_histogram(zs.zs_blocks_n_tenths_full, ZAP_HISTOGRAM_SIZE, 0);
1080
1081 (void) printf("\t\tEntries with n chunks:\n");
1082 dump_histogram(zs.zs_entries_using_n_chunks, ZAP_HISTOGRAM_SIZE, 0);
1083
1084 (void) printf("\t\tBuckets with n entries:\n");
1085 dump_histogram(zs.zs_buckets_with_n_entries, ZAP_HISTOGRAM_SIZE, 0);
1086 }
1087
1088 static void
1089 dump_none(objset_t *os, uint64_t object, void *data, size_t size)
1090 {
1091 (void) os, (void) object, (void) data, (void) size;
1092 }
1093
1094 static void
1095 dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
1096 {
1097 (void) os, (void) object, (void) data, (void) size;
1098 (void) printf("\tUNKNOWN OBJECT TYPE\n");
1099 }
1100
1101 static void
1102 dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
1103 {
1104 (void) os, (void) object, (void) data, (void) size;
1105 }
1106
1107 static void
1108 dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
1109 {
1110 uint64_t *arr;
1111 uint64_t oursize;
1112 if (dump_opt['d'] < 6)
1113 return;
1114
1115 if (data == NULL) {
1116 dmu_object_info_t doi;
1117
1118 VERIFY0(dmu_object_info(os, object, &doi));
1119 size = doi.doi_max_offset;
1120 /*
1121 * We cap the size at 1 mebibyte here to prevent
1122 * allocation failures and nigh-infinite printing if the
1123 * object is extremely large.
1124 */
1125 oursize = MIN(size, 1 << 20);
1126 arr = kmem_alloc(oursize, KM_SLEEP);
1127
1128 int err = dmu_read(os, object, 0, oursize, arr, 0);
1129 if (err != 0) {
1130 (void) printf("got error %u from dmu_read\n", err);
1131 kmem_free(arr, oursize);
1132 return;
1133 }
1134 } else {
1135 /*
1136 * Even though the allocation is already done in this code path,
1137 * we still cap the size to prevent excessive printing.
1138 */
1139 oursize = MIN(size, 1 << 20);
1140 arr = data;
1141 }
1142
1143 if (size == 0) {
1144 if (data == NULL)
1145 kmem_free(arr, oursize);
1146 (void) printf("\t\t[]\n");
1147 return;
1148 }
1149
1150 (void) printf("\t\t[%0llx", (u_longlong_t)arr[0]);
1151 for (size_t i = 1; i * sizeof (uint64_t) < oursize; i++) {
1152 if (i % 4 != 0)
1153 (void) printf(", %0llx", (u_longlong_t)arr[i]);
1154 else
1155 (void) printf(",\n\t\t%0llx", (u_longlong_t)arr[i]);
1156 }
1157 if (oursize != size)
1158 (void) printf(", ... ");
1159 (void) printf("]\n");
1160
1161 if (data == NULL)
1162 kmem_free(arr, oursize);
1163 }
1164
1165 static void
1166 dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
1167 {
1168 (void) data, (void) size;
1169 zap_cursor_t zc;
1170 zap_attribute_t attr;
1171 void *prop;
1172 unsigned i;
1173
1174 dump_zap_stats(os, object);
1175 (void) printf("\n");
1176
1177 for (zap_cursor_init(&zc, os, object);
1178 zap_cursor_retrieve(&zc, &attr) == 0;
1179 zap_cursor_advance(&zc)) {
1180 (void) printf("\t\t%s = ", attr.za_name);
1181 if (attr.za_num_integers == 0) {
1182 (void) printf("\n");
1183 continue;
1184 }
1185 prop = umem_zalloc(attr.za_num_integers *
1186 attr.za_integer_length, UMEM_NOFAIL);
1187 (void) zap_lookup(os, object, attr.za_name,
1188 attr.za_integer_length, attr.za_num_integers, prop);
1189 if (attr.za_integer_length == 1) {
1190 if (strcmp(attr.za_name,
1191 DSL_CRYPTO_KEY_MASTER_KEY) == 0 ||
1192 strcmp(attr.za_name,
1193 DSL_CRYPTO_KEY_HMAC_KEY) == 0 ||
1194 strcmp(attr.za_name, DSL_CRYPTO_KEY_IV) == 0 ||
1195 strcmp(attr.za_name, DSL_CRYPTO_KEY_MAC) == 0 ||
1196 strcmp(attr.za_name, DMU_POOL_CHECKSUM_SALT) == 0) {
1197 uint8_t *u8 = prop;
1198
1199 for (i = 0; i < attr.za_num_integers; i++) {
1200 (void) printf("%02x", u8[i]);
1201 }
1202 } else {
1203 (void) printf("%s", (char *)prop);
1204 }
1205 } else {
1206 for (i = 0; i < attr.za_num_integers; i++) {
1207 switch (attr.za_integer_length) {
1208 case 2:
1209 (void) printf("%u ",
1210 ((uint16_t *)prop)[i]);
1211 break;
1212 case 4:
1213 (void) printf("%u ",
1214 ((uint32_t *)prop)[i]);
1215 break;
1216 case 8:
1217 (void) printf("%lld ",
1218 (u_longlong_t)((int64_t *)prop)[i]);
1219 break;
1220 }
1221 }
1222 }
1223 (void) printf("\n");
1224 umem_free(prop, attr.za_num_integers * attr.za_integer_length);
1225 }
1226 zap_cursor_fini(&zc);
1227 }
1228
1229 static void
1230 dump_bpobj(objset_t *os, uint64_t object, void *data, size_t size)
1231 {
1232 bpobj_phys_t *bpop = data;
1233 uint64_t i;
1234 char bytes[32], comp[32], uncomp[32];
1235
1236 /* make sure the output won't get truncated */
1237 _Static_assert(sizeof (bytes) >= NN_NUMBUF_SZ, "bytes truncated");
1238 _Static_assert(sizeof (comp) >= NN_NUMBUF_SZ, "comp truncated");
1239 _Static_assert(sizeof (uncomp) >= NN_NUMBUF_SZ, "uncomp truncated");
1240
1241 if (bpop == NULL)
1242 return;
1243
1244 zdb_nicenum(bpop->bpo_bytes, bytes, sizeof (bytes));
1245 zdb_nicenum(bpop->bpo_comp, comp, sizeof (comp));
1246 zdb_nicenum(bpop->bpo_uncomp, uncomp, sizeof (uncomp));
1247
1248 (void) printf("\t\tnum_blkptrs = %llu\n",
1249 (u_longlong_t)bpop->bpo_num_blkptrs);
1250 (void) printf("\t\tbytes = %s\n", bytes);
1251 if (size >= BPOBJ_SIZE_V1) {
1252 (void) printf("\t\tcomp = %s\n", comp);
1253 (void) printf("\t\tuncomp = %s\n", uncomp);
1254 }
1255 if (size >= BPOBJ_SIZE_V2) {
1256 (void) printf("\t\tsubobjs = %llu\n",
1257 (u_longlong_t)bpop->bpo_subobjs);
1258 (void) printf("\t\tnum_subobjs = %llu\n",
1259 (u_longlong_t)bpop->bpo_num_subobjs);
1260 }
1261 if (size >= sizeof (*bpop)) {
1262 (void) printf("\t\tnum_freed = %llu\n",
1263 (u_longlong_t)bpop->bpo_num_freed);
1264 }
1265
1266 if (dump_opt['d'] < 5)
1267 return;
1268
1269 for (i = 0; i < bpop->bpo_num_blkptrs; i++) {
1270 char blkbuf[BP_SPRINTF_LEN];
1271 blkptr_t bp;
1272
1273 int err = dmu_read(os, object,
1274 i * sizeof (bp), sizeof (bp), &bp, 0);
1275 if (err != 0) {
1276 (void) printf("got error %u from dmu_read\n", err);
1277 break;
1278 }
1279 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), &bp,
1280 BP_GET_FREE(&bp));
1281 (void) printf("\t%s\n", blkbuf);
1282 }
1283 }
1284
1285 static void
1286 dump_bpobj_subobjs(objset_t *os, uint64_t object, void *data, size_t size)
1287 {
1288 (void) data, (void) size;
1289 dmu_object_info_t doi;
1290 int64_t i;
1291
1292 VERIFY0(dmu_object_info(os, object, &doi));
1293 uint64_t *subobjs = kmem_alloc(doi.doi_max_offset, KM_SLEEP);
1294
1295 int err = dmu_read(os, object, 0, doi.doi_max_offset, subobjs, 0);
1296 if (err != 0) {
1297 (void) printf("got error %u from dmu_read\n", err);
1298 kmem_free(subobjs, doi.doi_max_offset);
1299 return;
1300 }
1301
1302 int64_t last_nonzero = -1;
1303 for (i = 0; i < doi.doi_max_offset / 8; i++) {
1304 if (subobjs[i] != 0)
1305 last_nonzero = i;
1306 }
1307
1308 for (i = 0; i <= last_nonzero; i++) {
1309 (void) printf("\t%llu\n", (u_longlong_t)subobjs[i]);
1310 }
1311 kmem_free(subobjs, doi.doi_max_offset);
1312 }
1313
1314 static void
1315 dump_ddt_zap(objset_t *os, uint64_t object, void *data, size_t size)
1316 {
1317 (void) data, (void) size;
1318 dump_zap_stats(os, object);
1319 /* contents are printed elsewhere, properly decoded */
1320 }
1321
1322 static void
1323 dump_sa_attrs(objset_t *os, uint64_t object, void *data, size_t size)
1324 {
1325 (void) data, (void) size;
1326 zap_cursor_t zc;
1327 zap_attribute_t attr;
1328
1329 dump_zap_stats(os, object);
1330 (void) printf("\n");
1331
1332 for (zap_cursor_init(&zc, os, object);
1333 zap_cursor_retrieve(&zc, &attr) == 0;
1334 zap_cursor_advance(&zc)) {
1335 (void) printf("\t\t%s = ", attr.za_name);
1336 if (attr.za_num_integers == 0) {
1337 (void) printf("\n");
1338 continue;
1339 }
1340 (void) printf(" %llx : [%d:%d:%d]\n",
1341 (u_longlong_t)attr.za_first_integer,
1342 (int)ATTR_LENGTH(attr.za_first_integer),
1343 (int)ATTR_BSWAP(attr.za_first_integer),
1344 (int)ATTR_NUM(attr.za_first_integer));
1345 }
1346 zap_cursor_fini(&zc);
1347 }
1348
1349 static void
1350 dump_sa_layouts(objset_t *os, uint64_t object, void *data, size_t size)
1351 {
1352 (void) data, (void) size;
1353 zap_cursor_t zc;
1354 zap_attribute_t attr;
1355 uint16_t *layout_attrs;
1356 unsigned i;
1357
1358 dump_zap_stats(os, object);
1359 (void) printf("\n");
1360
1361 for (zap_cursor_init(&zc, os, object);
1362 zap_cursor_retrieve(&zc, &attr) == 0;
1363 zap_cursor_advance(&zc)) {
1364 (void) printf("\t\t%s = [", attr.za_name);
1365 if (attr.za_num_integers == 0) {
1366 (void) printf("\n");
1367 continue;
1368 }
1369
1370 VERIFY(attr.za_integer_length == 2);
1371 layout_attrs = umem_zalloc(attr.za_num_integers *
1372 attr.za_integer_length, UMEM_NOFAIL);
1373
1374 VERIFY(zap_lookup(os, object, attr.za_name,
1375 attr.za_integer_length,
1376 attr.za_num_integers, layout_attrs) == 0);
1377
1378 for (i = 0; i != attr.za_num_integers; i++)
1379 (void) printf(" %d ", (int)layout_attrs[i]);
1380 (void) printf("]\n");
1381 umem_free(layout_attrs,
1382 attr.za_num_integers * attr.za_integer_length);
1383 }
1384 zap_cursor_fini(&zc);
1385 }
1386
1387 static void
1388 dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
1389 {
1390 (void) data, (void) size;
1391 zap_cursor_t zc;
1392 zap_attribute_t attr;
1393 const char *typenames[] = {
1394 /* 0 */ "not specified",
1395 /* 1 */ "FIFO",
1396 /* 2 */ "Character Device",
1397 /* 3 */ "3 (invalid)",
1398 /* 4 */ "Directory",
1399 /* 5 */ "5 (invalid)",
1400 /* 6 */ "Block Device",
1401 /* 7 */ "7 (invalid)",
1402 /* 8 */ "Regular File",
1403 /* 9 */ "9 (invalid)",
1404 /* 10 */ "Symbolic Link",
1405 /* 11 */ "11 (invalid)",
1406 /* 12 */ "Socket",
1407 /* 13 */ "Door",
1408 /* 14 */ "Event Port",
1409 /* 15 */ "15 (invalid)",
1410 };
1411
1412 dump_zap_stats(os, object);
1413 (void) printf("\n");
1414
1415 for (zap_cursor_init(&zc, os, object);
1416 zap_cursor_retrieve(&zc, &attr) == 0;
1417 zap_cursor_advance(&zc)) {
1418 (void) printf("\t\t%s = %lld (type: %s)\n",
1419 attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
1420 typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
1421 }
1422 zap_cursor_fini(&zc);
1423 }
1424
1425 static int
1426 get_dtl_refcount(vdev_t *vd)
1427 {
1428 int refcount = 0;
1429
1430 if (vd->vdev_ops->vdev_op_leaf) {
1431 space_map_t *sm = vd->vdev_dtl_sm;
1432
1433 if (sm != NULL &&
1434 sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
1435 return (1);
1436 return (0);
1437 }
1438
1439 for (unsigned c = 0; c < vd->vdev_children; c++)
1440 refcount += get_dtl_refcount(vd->vdev_child[c]);
1441 return (refcount);
1442 }
1443
1444 static int
1445 get_metaslab_refcount(vdev_t *vd)
1446 {
1447 int refcount = 0;
1448
1449 if (vd->vdev_top == vd) {
1450 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
1451 space_map_t *sm = vd->vdev_ms[m]->ms_sm;
1452
1453 if (sm != NULL &&
1454 sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
1455 refcount++;
1456 }
1457 }
1458 for (unsigned c = 0; c < vd->vdev_children; c++)
1459 refcount += get_metaslab_refcount(vd->vdev_child[c]);
1460
1461 return (refcount);
1462 }
1463
1464 static int
1465 get_obsolete_refcount(vdev_t *vd)
1466 {
1467 uint64_t obsolete_sm_object;
1468 int refcount = 0;
1469
1470 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
1471 if (vd->vdev_top == vd && obsolete_sm_object != 0) {
1472 dmu_object_info_t doi;
1473 VERIFY0(dmu_object_info(vd->vdev_spa->spa_meta_objset,
1474 obsolete_sm_object, &doi));
1475 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
1476 refcount++;
1477 }
1478 } else {
1479 ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
1480 ASSERT3U(obsolete_sm_object, ==, 0);
1481 }
1482 for (unsigned c = 0; c < vd->vdev_children; c++) {
1483 refcount += get_obsolete_refcount(vd->vdev_child[c]);
1484 }
1485
1486 return (refcount);
1487 }
1488
1489 static int
1490 get_prev_obsolete_spacemap_refcount(spa_t *spa)
1491 {
1492 uint64_t prev_obj =
1493 spa->spa_condensing_indirect_phys.scip_prev_obsolete_sm_object;
1494 if (prev_obj != 0) {
1495 dmu_object_info_t doi;
1496 VERIFY0(dmu_object_info(spa->spa_meta_objset, prev_obj, &doi));
1497 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
1498 return (1);
1499 }
1500 }
1501 return (0);
1502 }
1503
1504 static int
1505 get_checkpoint_refcount(vdev_t *vd)
1506 {
1507 int refcount = 0;
1508
1509 if (vd->vdev_top == vd && vd->vdev_top_zap != 0 &&
1510 zap_contains(spa_meta_objset(vd->vdev_spa),
1511 vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) == 0)
1512 refcount++;
1513
1514 for (uint64_t c = 0; c < vd->vdev_children; c++)
1515 refcount += get_checkpoint_refcount(vd->vdev_child[c]);
1516
1517 return (refcount);
1518 }
1519
1520 static int
1521 get_log_spacemap_refcount(spa_t *spa)
1522 {
1523 return (avl_numnodes(&spa->spa_sm_logs_by_txg));
1524 }
1525
1526 static int
1527 verify_spacemap_refcounts(spa_t *spa)
1528 {
1529 uint64_t expected_refcount = 0;
1530 uint64_t actual_refcount;
1531
1532 (void) feature_get_refcount(spa,
1533 &spa_feature_table[SPA_FEATURE_SPACEMAP_HISTOGRAM],
1534 &expected_refcount);
1535 actual_refcount = get_dtl_refcount(spa->spa_root_vdev);
1536 actual_refcount += get_metaslab_refcount(spa->spa_root_vdev);
1537 actual_refcount += get_obsolete_refcount(spa->spa_root_vdev);
1538 actual_refcount += get_prev_obsolete_spacemap_refcount(spa);
1539 actual_refcount += get_checkpoint_refcount(spa->spa_root_vdev);
1540 actual_refcount += get_log_spacemap_refcount(spa);
1541
1542 if (expected_refcount != actual_refcount) {
1543 (void) printf("space map refcount mismatch: expected %lld != "
1544 "actual %lld\n",
1545 (longlong_t)expected_refcount,
1546 (longlong_t)actual_refcount);
1547 return (2);
1548 }
1549 return (0);
1550 }
1551
1552 static void
1553 dump_spacemap(objset_t *os, space_map_t *sm)
1554 {
1555 const char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
1556 "INVALID", "INVALID", "INVALID", "INVALID" };
1557
1558 if (sm == NULL)
1559 return;
1560
1561 (void) printf("space map object %llu:\n",
1562 (longlong_t)sm->sm_object);
1563 (void) printf(" smp_length = 0x%llx\n",
1564 (longlong_t)sm->sm_phys->smp_length);
1565 (void) printf(" smp_alloc = 0x%llx\n",
1566 (longlong_t)sm->sm_phys->smp_alloc);
1567
1568 if (dump_opt['d'] < 6 && dump_opt['m'] < 4)
1569 return;
1570
1571 /*
1572 * Print out the freelist entries in both encoded and decoded form.
1573 */
1574 uint8_t mapshift = sm->sm_shift;
1575 int64_t alloc = 0;
1576 uint64_t word, entry_id = 0;
1577 for (uint64_t offset = 0; offset < space_map_length(sm);
1578 offset += sizeof (word)) {
1579
1580 VERIFY0(dmu_read(os, space_map_object(sm), offset,
1581 sizeof (word), &word, DMU_READ_PREFETCH));
1582
1583 if (sm_entry_is_debug(word)) {
1584 uint64_t de_txg = SM_DEBUG_TXG_DECODE(word);
1585 uint64_t de_sync_pass = SM_DEBUG_SYNCPASS_DECODE(word);
1586 if (de_txg == 0) {
1587 (void) printf(
1588 "\t [%6llu] PADDING\n",
1589 (u_longlong_t)entry_id);
1590 } else {
1591 (void) printf(
1592 "\t [%6llu] %s: txg %llu pass %llu\n",
1593 (u_longlong_t)entry_id,
1594 ddata[SM_DEBUG_ACTION_DECODE(word)],
1595 (u_longlong_t)de_txg,
1596 (u_longlong_t)de_sync_pass);
1597 }
1598 entry_id++;
1599 continue;
1600 }
1601
1602 uint8_t words;
1603 char entry_type;
1604 uint64_t entry_off, entry_run, entry_vdev = SM_NO_VDEVID;
1605
1606 if (sm_entry_is_single_word(word)) {
1607 entry_type = (SM_TYPE_DECODE(word) == SM_ALLOC) ?
1608 'A' : 'F';
1609 entry_off = (SM_OFFSET_DECODE(word) << mapshift) +
1610 sm->sm_start;
1611 entry_run = SM_RUN_DECODE(word) << mapshift;
1612 words = 1;
1613 } else {
1614 /* it is a two-word entry so we read another word */
1615 ASSERT(sm_entry_is_double_word(word));
1616
1617 uint64_t extra_word;
1618 offset += sizeof (extra_word);
1619 VERIFY0(dmu_read(os, space_map_object(sm), offset,
1620 sizeof (extra_word), &extra_word,
1621 DMU_READ_PREFETCH));
1622
1623 ASSERT3U(offset, <=, space_map_length(sm));
1624
1625 entry_run = SM2_RUN_DECODE(word) << mapshift;
1626 entry_vdev = SM2_VDEV_DECODE(word);
1627 entry_type = (SM2_TYPE_DECODE(extra_word) == SM_ALLOC) ?
1628 'A' : 'F';
1629 entry_off = (SM2_OFFSET_DECODE(extra_word) <<
1630 mapshift) + sm->sm_start;
1631 words = 2;
1632 }
1633
1634 (void) printf("\t [%6llu] %c range:"
1635 " %010llx-%010llx size: %06llx vdev: %06llu words: %u\n",
1636 (u_longlong_t)entry_id,
1637 entry_type, (u_longlong_t)entry_off,
1638 (u_longlong_t)(entry_off + entry_run),
1639 (u_longlong_t)entry_run,
1640 (u_longlong_t)entry_vdev, words);
1641
1642 if (entry_type == 'A')
1643 alloc += entry_run;
1644 else
1645 alloc -= entry_run;
1646 entry_id++;
1647 }
1648 if (alloc != space_map_allocated(sm)) {
1649 (void) printf("space_map_object alloc (%lld) INCONSISTENT "
1650 "with space map summary (%lld)\n",
1651 (longlong_t)space_map_allocated(sm), (longlong_t)alloc);
1652 }
1653 }
1654
1655 static void
1656 dump_metaslab_stats(metaslab_t *msp)
1657 {
1658 char maxbuf[32];
1659 range_tree_t *rt = msp->ms_allocatable;
1660 zfs_btree_t *t = &msp->ms_allocatable_by_size;
1661 int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
1662
1663 /* max sure nicenum has enough space */
1664 _Static_assert(sizeof (maxbuf) >= NN_NUMBUF_SZ, "maxbuf truncated");
1665
1666 zdb_nicenum(metaslab_largest_allocatable(msp), maxbuf, sizeof (maxbuf));
1667
1668 (void) printf("\t %25s %10lu %7s %6s %4s %4d%%\n",
1669 "segments", zfs_btree_numnodes(t), "maxsize", maxbuf,
1670 "freepct", free_pct);
1671 (void) printf("\tIn-memory histogram:\n");
1672 dump_histogram(rt->rt_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1673 }
1674
1675 static void
1676 dump_metaslab(metaslab_t *msp)
1677 {
1678 vdev_t *vd = msp->ms_group->mg_vd;
1679 spa_t *spa = vd->vdev_spa;
1680 space_map_t *sm = msp->ms_sm;
1681 char freebuf[32];
1682
1683 zdb_nicenum(msp->ms_size - space_map_allocated(sm), freebuf,
1684 sizeof (freebuf));
1685
1686 (void) printf(
1687 "\tmetaslab %6llu offset %12llx spacemap %6llu free %5s\n",
1688 (u_longlong_t)msp->ms_id, (u_longlong_t)msp->ms_start,
1689 (u_longlong_t)space_map_object(sm), freebuf);
1690
1691 if (dump_opt['m'] > 2 && !dump_opt['L']) {
1692 mutex_enter(&msp->ms_lock);
1693 VERIFY0(metaslab_load(msp));
1694 range_tree_stat_verify(msp->ms_allocatable);
1695 dump_metaslab_stats(msp);
1696 metaslab_unload(msp);
1697 mutex_exit(&msp->ms_lock);
1698 }
1699
1700 if (dump_opt['m'] > 1 && sm != NULL &&
1701 spa_feature_is_active(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
1702 /*
1703 * The space map histogram represents free space in chunks
1704 * of sm_shift (i.e. bucket 0 refers to 2^sm_shift).
1705 */
1706 (void) printf("\tOn-disk histogram:\t\tfragmentation %llu\n",
1707 (u_longlong_t)msp->ms_fragmentation);
1708 dump_histogram(sm->sm_phys->smp_histogram,
1709 SPACE_MAP_HISTOGRAM_SIZE, sm->sm_shift);
1710 }
1711
1712 if (vd->vdev_ops == &vdev_draid_ops)
1713 ASSERT3U(msp->ms_size, <=, 1ULL << vd->vdev_ms_shift);
1714 else
1715 ASSERT3U(msp->ms_size, ==, 1ULL << vd->vdev_ms_shift);
1716
1717 dump_spacemap(spa->spa_meta_objset, msp->ms_sm);
1718
1719 if (spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP)) {
1720 (void) printf("\tFlush data:\n\tunflushed txg=%llu\n\n",
1721 (u_longlong_t)metaslab_unflushed_txg(msp));
1722 }
1723 }
1724
1725 static void
1726 print_vdev_metaslab_header(vdev_t *vd)
1727 {
1728 vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
1729 const char *bias_str = "";
1730 if (alloc_bias == VDEV_BIAS_LOG || vd->vdev_islog) {
1731 bias_str = VDEV_ALLOC_BIAS_LOG;
1732 } else if (alloc_bias == VDEV_BIAS_SPECIAL) {
1733 bias_str = VDEV_ALLOC_BIAS_SPECIAL;
1734 } else if (alloc_bias == VDEV_BIAS_DEDUP) {
1735 bias_str = VDEV_ALLOC_BIAS_DEDUP;
1736 }
1737
1738 uint64_t ms_flush_data_obj = 0;
1739 if (vd->vdev_top_zap != 0) {
1740 int error = zap_lookup(spa_meta_objset(vd->vdev_spa),
1741 vd->vdev_top_zap, VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS,
1742 sizeof (uint64_t), 1, &ms_flush_data_obj);
1743 if (error != ENOENT) {
1744 ASSERT0(error);
1745 }
1746 }
1747
1748 (void) printf("\tvdev %10llu %s",
1749 (u_longlong_t)vd->vdev_id, bias_str);
1750
1751 if (ms_flush_data_obj != 0) {
1752 (void) printf(" ms_unflushed_phys object %llu",
1753 (u_longlong_t)ms_flush_data_obj);
1754 }
1755
1756 (void) printf("\n\t%-10s%5llu %-19s %-15s %-12s\n",
1757 "metaslabs", (u_longlong_t)vd->vdev_ms_count,
1758 "offset", "spacemap", "free");
1759 (void) printf("\t%15s %19s %15s %12s\n",
1760 "---------------", "-------------------",
1761 "---------------", "------------");
1762 }
1763
1764 static void
1765 dump_metaslab_groups(spa_t *spa, boolean_t show_special)
1766 {
1767 vdev_t *rvd = spa->spa_root_vdev;
1768 metaslab_class_t *mc = spa_normal_class(spa);
1769 metaslab_class_t *smc = spa_special_class(spa);
1770 uint64_t fragmentation;
1771
1772 metaslab_class_histogram_verify(mc);
1773
1774 for (unsigned c = 0; c < rvd->vdev_children; c++) {
1775 vdev_t *tvd = rvd->vdev_child[c];
1776 metaslab_group_t *mg = tvd->vdev_mg;
1777
1778 if (mg == NULL || (mg->mg_class != mc &&
1779 (!show_special || mg->mg_class != smc)))
1780 continue;
1781
1782 metaslab_group_histogram_verify(mg);
1783 mg->mg_fragmentation = metaslab_group_fragmentation(mg);
1784
1785 (void) printf("\tvdev %10llu\t\tmetaslabs%5llu\t\t"
1786 "fragmentation",
1787 (u_longlong_t)tvd->vdev_id,
1788 (u_longlong_t)tvd->vdev_ms_count);
1789 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
1790 (void) printf("%3s\n", "-");
1791 } else {
1792 (void) printf("%3llu%%\n",
1793 (u_longlong_t)mg->mg_fragmentation);
1794 }
1795 dump_histogram(mg->mg_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1796 }
1797
1798 (void) printf("\tpool %s\tfragmentation", spa_name(spa));
1799 fragmentation = metaslab_class_fragmentation(mc);
1800 if (fragmentation == ZFS_FRAG_INVALID)
1801 (void) printf("\t%3s\n", "-");
1802 else
1803 (void) printf("\t%3llu%%\n", (u_longlong_t)fragmentation);
1804 dump_histogram(mc->mc_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1805 }
1806
1807 static void
1808 print_vdev_indirect(vdev_t *vd)
1809 {
1810 vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
1811 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
1812 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
1813
1814 if (vim == NULL) {
1815 ASSERT3P(vib, ==, NULL);
1816 return;
1817 }
1818
1819 ASSERT3U(vdev_indirect_mapping_object(vim), ==,
1820 vic->vic_mapping_object);
1821 ASSERT3U(vdev_indirect_births_object(vib), ==,
1822 vic->vic_births_object);
1823
1824 (void) printf("indirect births obj %llu:\n",
1825 (longlong_t)vic->vic_births_object);
1826 (void) printf(" vib_count = %llu\n",
1827 (longlong_t)vdev_indirect_births_count(vib));
1828 for (uint64_t i = 0; i < vdev_indirect_births_count(vib); i++) {
1829 vdev_indirect_birth_entry_phys_t *cur_vibe =
1830 &vib->vib_entries[i];
1831 (void) printf("\toffset %llx -> txg %llu\n",
1832 (longlong_t)cur_vibe->vibe_offset,
1833 (longlong_t)cur_vibe->vibe_phys_birth_txg);
1834 }
1835 (void) printf("\n");
1836
1837 (void) printf("indirect mapping obj %llu:\n",
1838 (longlong_t)vic->vic_mapping_object);
1839 (void) printf(" vim_max_offset = 0x%llx\n",
1840 (longlong_t)vdev_indirect_mapping_max_offset(vim));
1841 (void) printf(" vim_bytes_mapped = 0x%llx\n",
1842 (longlong_t)vdev_indirect_mapping_bytes_mapped(vim));
1843 (void) printf(" vim_count = %llu\n",
1844 (longlong_t)vdev_indirect_mapping_num_entries(vim));
1845
1846 if (dump_opt['d'] <= 5 && dump_opt['m'] <= 3)
1847 return;
1848
1849 uint32_t *counts = vdev_indirect_mapping_load_obsolete_counts(vim);
1850
1851 for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
1852 vdev_indirect_mapping_entry_phys_t *vimep =
1853 &vim->vim_entries[i];
1854 (void) printf("\t<%llx:%llx:%llx> -> "
1855 "<%llx:%llx:%llx> (%x obsolete)\n",
1856 (longlong_t)vd->vdev_id,
1857 (longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
1858 (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1859 (longlong_t)DVA_GET_VDEV(&vimep->vimep_dst),
1860 (longlong_t)DVA_GET_OFFSET(&vimep->vimep_dst),
1861 (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1862 counts[i]);
1863 }
1864 (void) printf("\n");
1865
1866 uint64_t obsolete_sm_object;
1867 VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
1868 if (obsolete_sm_object != 0) {
1869 objset_t *mos = vd->vdev_spa->spa_meta_objset;
1870 (void) printf("obsolete space map object %llu:\n",
1871 (u_longlong_t)obsolete_sm_object);
1872 ASSERT(vd->vdev_obsolete_sm != NULL);
1873 ASSERT3U(space_map_object(vd->vdev_obsolete_sm), ==,
1874 obsolete_sm_object);
1875 dump_spacemap(mos, vd->vdev_obsolete_sm);
1876 (void) printf("\n");
1877 }
1878 }
1879
1880 static void
1881 dump_metaslabs(spa_t *spa)
1882 {
1883 vdev_t *vd, *rvd = spa->spa_root_vdev;
1884 uint64_t m, c = 0, children = rvd->vdev_children;
1885
1886 (void) printf("\nMetaslabs:\n");
1887
1888 if (!dump_opt['d'] && zopt_metaslab_args > 0) {
1889 c = zopt_metaslab[0];
1890
1891 if (c >= children)
1892 (void) fatal("bad vdev id: %llu", (u_longlong_t)c);
1893
1894 if (zopt_metaslab_args > 1) {
1895 vd = rvd->vdev_child[c];
1896 print_vdev_metaslab_header(vd);
1897
1898 for (m = 1; m < zopt_metaslab_args; m++) {
1899 if (zopt_metaslab[m] < vd->vdev_ms_count)
1900 dump_metaslab(
1901 vd->vdev_ms[zopt_metaslab[m]]);
1902 else
1903 (void) fprintf(stderr, "bad metaslab "
1904 "number %llu\n",
1905 (u_longlong_t)zopt_metaslab[m]);
1906 }
1907 (void) printf("\n");
1908 return;
1909 }
1910 children = c + 1;
1911 }
1912 for (; c < children; c++) {
1913 vd = rvd->vdev_child[c];
1914 print_vdev_metaslab_header(vd);
1915
1916 print_vdev_indirect(vd);
1917
1918 for (m = 0; m < vd->vdev_ms_count; m++)
1919 dump_metaslab(vd->vdev_ms[m]);
1920 (void) printf("\n");
1921 }
1922 }
1923
1924 static void
1925 dump_log_spacemaps(spa_t *spa)
1926 {
1927 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
1928 return;
1929
1930 (void) printf("\nLog Space Maps in Pool:\n");
1931 for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
1932 sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls)) {
1933 space_map_t *sm = NULL;
1934 VERIFY0(space_map_open(&sm, spa_meta_objset(spa),
1935 sls->sls_sm_obj, 0, UINT64_MAX, SPA_MINBLOCKSHIFT));
1936
1937 (void) printf("Log Spacemap object %llu txg %llu\n",
1938 (u_longlong_t)sls->sls_sm_obj, (u_longlong_t)sls->sls_txg);
1939 dump_spacemap(spa->spa_meta_objset, sm);
1940 space_map_close(sm);
1941 }
1942 (void) printf("\n");
1943 }
1944
1945 static void
1946 dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
1947 {
1948 const ddt_phys_t *ddp = dde->dde_phys;
1949 const ddt_key_t *ddk = &dde->dde_key;
1950 const char *types[4] = { "ditto", "single", "double", "triple" };
1951 char blkbuf[BP_SPRINTF_LEN];
1952 blkptr_t blk;
1953 int p;
1954
1955 for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1956 if (ddp->ddp_phys_birth == 0)
1957 continue;
1958 ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
1959 snprintf_blkptr(blkbuf, sizeof (blkbuf), &blk);
1960 (void) printf("index %llx refcnt %llu %s %s\n",
1961 (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
1962 types[p], blkbuf);
1963 }
1964 }
1965
1966 static void
1967 dump_dedup_ratio(const ddt_stat_t *dds)
1968 {
1969 double rL, rP, rD, D, dedup, compress, copies;
1970
1971 if (dds->dds_blocks == 0)
1972 return;
1973
1974 rL = (double)dds->dds_ref_lsize;
1975 rP = (double)dds->dds_ref_psize;
1976 rD = (double)dds->dds_ref_dsize;
1977 D = (double)dds->dds_dsize;
1978
1979 dedup = rD / D;
1980 compress = rL / rP;
1981 copies = rD / rP;
1982
1983 (void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
1984 "dedup * compress / copies = %.2f\n\n",
1985 dedup, compress, copies, dedup * compress / copies);
1986 }
1987
1988 static void
1989 dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
1990 {
1991 char name[DDT_NAMELEN];
1992 ddt_entry_t dde;
1993 uint64_t walk = 0;
1994 dmu_object_info_t doi;
1995 uint64_t count, dspace, mspace;
1996 int error;
1997
1998 error = ddt_object_info(ddt, type, class, &doi);
1999
2000 if (error == ENOENT)
2001 return;
2002 ASSERT(error == 0);
2003
2004 error = ddt_object_count(ddt, type, class, &count);
2005 ASSERT(error == 0);
2006 if (count == 0)
2007 return;
2008
2009 dspace = doi.doi_physical_blocks_512 << 9;
2010 mspace = doi.doi_fill_count * doi.doi_data_block_size;
2011
2012 ddt_object_name(ddt, type, class, name);
2013
2014 (void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
2015 name,
2016 (u_longlong_t)count,
2017 (u_longlong_t)(dspace / count),
2018 (u_longlong_t)(mspace / count));
2019
2020 if (dump_opt['D'] < 3)
2021 return;
2022
2023 zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
2024
2025 if (dump_opt['D'] < 4)
2026 return;
2027
2028 if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
2029 return;
2030
2031 (void) printf("%s contents:\n\n", name);
2032
2033 while ((error = ddt_object_walk(ddt, type, class, &walk, &dde)) == 0)
2034 dump_dde(ddt, &dde, walk);
2035
2036 ASSERT3U(error, ==, ENOENT);
2037
2038 (void) printf("\n");
2039 }
2040
2041 static void
2042 dump_all_ddts(spa_t *spa)
2043 {
2044 ddt_histogram_t ddh_total = {{{0}}};
2045 ddt_stat_t dds_total = {0};
2046
2047 for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
2048 ddt_t *ddt = spa->spa_ddt[c];
2049 for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
2050 for (enum ddt_class class = 0; class < DDT_CLASSES;
2051 class++) {
2052 dump_ddt(ddt, type, class);
2053 }
2054 }
2055 }
2056
2057 ddt_get_dedup_stats(spa, &dds_total);
2058
2059 if (dds_total.dds_blocks == 0) {
2060 (void) printf("All DDTs are empty\n");
2061 return;
2062 }
2063
2064 (void) printf("\n");
2065
2066 if (dump_opt['D'] > 1) {
2067 (void) printf("DDT histogram (aggregated over all DDTs):\n");
2068 ddt_get_dedup_histogram(spa, &ddh_total);
2069 zpool_dump_ddt(&dds_total, &ddh_total);
2070 }
2071
2072 dump_dedup_ratio(&dds_total);
2073 }
2074
2075 static void
2076 dump_dtl_seg(void *arg, uint64_t start, uint64_t size)
2077 {
2078 char *prefix = arg;
2079
2080 (void) printf("%s [%llu,%llu) length %llu\n",
2081 prefix,
2082 (u_longlong_t)start,
2083 (u_longlong_t)(start + size),
2084 (u_longlong_t)(size));
2085 }
2086
2087 static void
2088 dump_dtl(vdev_t *vd, int indent)
2089 {
2090 spa_t *spa = vd->vdev_spa;
2091 boolean_t required;
2092 const char *name[DTL_TYPES] = { "missing", "partial", "scrub",
2093 "outage" };
2094 char prefix[256];
2095
2096 spa_vdev_state_enter(spa, SCL_NONE);
2097 required = vdev_dtl_required(vd);
2098 (void) spa_vdev_state_exit(spa, NULL, 0);
2099
2100 if (indent == 0)
2101 (void) printf("\nDirty time logs:\n\n");
2102
2103 (void) printf("\t%*s%s [%s]\n", indent, "",
2104 vd->vdev_path ? vd->vdev_path :
2105 vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
2106 required ? "DTL-required" : "DTL-expendable");
2107
2108 for (int t = 0; t < DTL_TYPES; t++) {
2109 range_tree_t *rt = vd->vdev_dtl[t];
2110 if (range_tree_space(rt) == 0)
2111 continue;
2112 (void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
2113 indent + 2, "", name[t]);
2114 range_tree_walk(rt, dump_dtl_seg, prefix);
2115 if (dump_opt['d'] > 5 && vd->vdev_children == 0)
2116 dump_spacemap(spa->spa_meta_objset,
2117 vd->vdev_dtl_sm);
2118 }
2119
2120 for (unsigned c = 0; c < vd->vdev_children; c++)
2121 dump_dtl(vd->vdev_child[c], indent + 4);
2122 }
2123
2124 static void
2125 dump_history(spa_t *spa)
2126 {
2127 nvlist_t **events = NULL;
2128 char *buf;
2129 uint64_t resid, len, off = 0;
2130 uint_t num = 0;
2131 int error;
2132 char tbuf[30];
2133
2134 if ((buf = malloc(SPA_OLD_MAXBLOCKSIZE)) == NULL) {
2135 (void) fprintf(stderr, "%s: unable to allocate I/O buffer\n",
2136 __func__);
2137 return;
2138 }
2139
2140 do {
2141 len = SPA_OLD_MAXBLOCKSIZE;
2142
2143 if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
2144 (void) fprintf(stderr, "Unable to read history: "
2145 "error %d\n", error);
2146 free(buf);
2147 return;
2148 }
2149
2150 if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
2151 break;
2152
2153 off -= resid;
2154 } while (len != 0);
2155
2156 (void) printf("\nHistory:\n");
2157 for (unsigned i = 0; i < num; i++) {
2158 boolean_t printed = B_FALSE;
2159
2160 if (nvlist_exists(events[i], ZPOOL_HIST_TIME)) {
2161 time_t tsec;
2162 struct tm t;
2163
2164 tsec = fnvlist_lookup_uint64(events[i],
2165 ZPOOL_HIST_TIME);
2166 (void) localtime_r(&tsec, &t);
2167 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
2168 } else {
2169 tbuf[0] = '\0';
2170 }
2171
2172 if (nvlist_exists(events[i], ZPOOL_HIST_CMD)) {
2173 (void) printf("%s %s\n", tbuf,
2174 fnvlist_lookup_string(events[i], ZPOOL_HIST_CMD));
2175 } else if (nvlist_exists(events[i], ZPOOL_HIST_INT_EVENT)) {
2176 uint64_t ievent;
2177
2178 ievent = fnvlist_lookup_uint64(events[i],
2179 ZPOOL_HIST_INT_EVENT);
2180 if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
2181 goto next;
2182
2183 (void) printf(" %s [internal %s txg:%ju] %s\n",
2184 tbuf,
2185 zfs_history_event_names[ievent],
2186 fnvlist_lookup_uint64(events[i],
2187 ZPOOL_HIST_TXG),
2188 fnvlist_lookup_string(events[i],
2189 ZPOOL_HIST_INT_STR));
2190 } else if (nvlist_exists(events[i], ZPOOL_HIST_INT_NAME)) {
2191 (void) printf("%s [txg:%ju] %s", tbuf,
2192 fnvlist_lookup_uint64(events[i],
2193 ZPOOL_HIST_TXG),
2194 fnvlist_lookup_string(events[i],
2195 ZPOOL_HIST_INT_NAME));
2196
2197 if (nvlist_exists(events[i], ZPOOL_HIST_DSNAME)) {
2198 (void) printf(" %s (%llu)",
2199 fnvlist_lookup_string(events[i],
2200 ZPOOL_HIST_DSNAME),
2201 (u_longlong_t)fnvlist_lookup_uint64(
2202 events[i],
2203 ZPOOL_HIST_DSID));
2204 }
2205
2206 (void) printf(" %s\n", fnvlist_lookup_string(events[i],
2207 ZPOOL_HIST_INT_STR));
2208 } else if (nvlist_exists(events[i], ZPOOL_HIST_IOCTL)) {
2209 (void) printf("%s ioctl %s\n", tbuf,
2210 fnvlist_lookup_string(events[i],
2211 ZPOOL_HIST_IOCTL));
2212
2213 if (nvlist_exists(events[i], ZPOOL_HIST_INPUT_NVL)) {
2214 (void) printf(" input:\n");
2215 dump_nvlist(fnvlist_lookup_nvlist(events[i],
2216 ZPOOL_HIST_INPUT_NVL), 8);
2217 }
2218 if (nvlist_exists(events[i], ZPOOL_HIST_OUTPUT_NVL)) {
2219 (void) printf(" output:\n");
2220 dump_nvlist(fnvlist_lookup_nvlist(events[i],
2221 ZPOOL_HIST_OUTPUT_NVL), 8);
2222 }
2223 if (nvlist_exists(events[i], ZPOOL_HIST_ERRNO)) {
2224 (void) printf(" errno: %lld\n",
2225 (longlong_t)fnvlist_lookup_int64(events[i],
2226 ZPOOL_HIST_ERRNO));
2227 }
2228 } else {
2229 goto next;
2230 }
2231
2232 printed = B_TRUE;
2233 next:
2234 if (dump_opt['h'] > 1) {
2235 if (!printed)
2236 (void) printf("unrecognized record:\n");
2237 dump_nvlist(events[i], 2);
2238 }
2239 }
2240 free(buf);
2241 }
2242
2243 static void
2244 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
2245 {
2246 (void) os, (void) object, (void) data, (void) size;
2247 }
2248
2249 static uint64_t
2250 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp,
2251 const zbookmark_phys_t *zb)
2252 {
2253 if (dnp == NULL) {
2254 ASSERT(zb->zb_level < 0);
2255 if (zb->zb_object == 0)
2256 return (zb->zb_blkid);
2257 return (zb->zb_blkid * BP_GET_LSIZE(bp));
2258 }
2259
2260 ASSERT(zb->zb_level >= 0);
2261
2262 return ((zb->zb_blkid <<
2263 (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
2264 dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
2265 }
2266
2267 static void
2268 snprintf_zstd_header(spa_t *spa, char *blkbuf, size_t buflen,
2269 const blkptr_t *bp)
2270 {
2271 abd_t *pabd;
2272 void *buf;
2273 zio_t *zio;
2274 zfs_zstdhdr_t zstd_hdr;
2275 int error;
2276
2277 if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_ZSTD)
2278 return;
2279
2280 if (BP_IS_HOLE(bp))
2281 return;
2282
2283 if (BP_IS_EMBEDDED(bp)) {
2284 buf = malloc(SPA_MAXBLOCKSIZE);
2285 if (buf == NULL) {
2286 (void) fprintf(stderr, "out of memory\n");
2287 exit(1);
2288 }
2289 decode_embedded_bp_compressed(bp, buf);
2290 memcpy(&zstd_hdr, buf, sizeof (zstd_hdr));
2291 free(buf);
2292 zstd_hdr.c_len = BE_32(zstd_hdr.c_len);
2293 zstd_hdr.raw_version_level = BE_32(zstd_hdr.raw_version_level);
2294 (void) snprintf(blkbuf + strlen(blkbuf),
2295 buflen - strlen(blkbuf),
2296 " ZSTD:size=%u:version=%u:level=%u:EMBEDDED",
2297 zstd_hdr.c_len, zfs_get_hdrversion(&zstd_hdr),
2298 zfs_get_hdrlevel(&zstd_hdr));
2299 return;
2300 }
2301
2302 pabd = abd_alloc_for_io(SPA_MAXBLOCKSIZE, B_FALSE);
2303 zio = zio_root(spa, NULL, NULL, 0);
2304
2305 /* Decrypt but don't decompress so we can read the compression header */
2306 zio_nowait(zio_read(zio, spa, bp, pabd, BP_GET_PSIZE(bp), NULL, NULL,
2307 ZIO_PRIORITY_SYNC_READ, ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW_COMPRESS,
2308 NULL));
2309 error = zio_wait(zio);
2310 if (error) {
2311 (void) fprintf(stderr, "read failed: %d\n", error);
2312 return;
2313 }
2314 buf = abd_borrow_buf_copy(pabd, BP_GET_LSIZE(bp));
2315 memcpy(&zstd_hdr, buf, sizeof (zstd_hdr));
2316 zstd_hdr.c_len = BE_32(zstd_hdr.c_len);
2317 zstd_hdr.raw_version_level = BE_32(zstd_hdr.raw_version_level);
2318
2319 (void) snprintf(blkbuf + strlen(blkbuf),
2320 buflen - strlen(blkbuf),
2321 " ZSTD:size=%u:version=%u:level=%u:NORMAL",
2322 zstd_hdr.c_len, zfs_get_hdrversion(&zstd_hdr),
2323 zfs_get_hdrlevel(&zstd_hdr));
2324
2325 abd_return_buf_copy(pabd, buf, BP_GET_LSIZE(bp));
2326 }
2327
2328 static void
2329 snprintf_blkptr_compact(char *blkbuf, size_t buflen, const blkptr_t *bp,
2330 boolean_t bp_freed)
2331 {
2332 const dva_t *dva = bp->blk_dva;
2333 int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
2334 int i;
2335
2336 if (dump_opt['b'] >= 6) {
2337 snprintf_blkptr(blkbuf, buflen, bp);
2338 if (bp_freed) {
2339 (void) snprintf(blkbuf + strlen(blkbuf),
2340 buflen - strlen(blkbuf), " %s", "FREE");
2341 }
2342 return;
2343 }
2344
2345 if (BP_IS_EMBEDDED(bp)) {
2346 (void) sprintf(blkbuf,
2347 "EMBEDDED et=%u %llxL/%llxP B=%llu",
2348 (int)BPE_GET_ETYPE(bp),
2349 (u_longlong_t)BPE_GET_LSIZE(bp),
2350 (u_longlong_t)BPE_GET_PSIZE(bp),
2351 (u_longlong_t)bp->blk_birth);
2352 return;
2353 }
2354
2355 blkbuf[0] = '\0';
2356
2357 for (i = 0; i < ndvas; i++)
2358 (void) snprintf(blkbuf + strlen(blkbuf),
2359 buflen - strlen(blkbuf), "%llu:%llx:%llx ",
2360 (u_longlong_t)DVA_GET_VDEV(&dva[i]),
2361 (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
2362 (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
2363
2364 if (BP_IS_HOLE(bp)) {
2365 (void) snprintf(blkbuf + strlen(blkbuf),
2366 buflen - strlen(blkbuf),
2367 "%llxL B=%llu",
2368 (u_longlong_t)BP_GET_LSIZE(bp),
2369 (u_longlong_t)bp->blk_birth);
2370 } else {
2371 (void) snprintf(blkbuf + strlen(blkbuf),
2372 buflen - strlen(blkbuf),
2373 "%llxL/%llxP F=%llu B=%llu/%llu",
2374 (u_longlong_t)BP_GET_LSIZE(bp),
2375 (u_longlong_t)BP_GET_PSIZE(bp),
2376 (u_longlong_t)BP_GET_FILL(bp),
2377 (u_longlong_t)bp->blk_birth,
2378 (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
2379 if (bp_freed)
2380 (void) snprintf(blkbuf + strlen(blkbuf),
2381 buflen - strlen(blkbuf), " %s", "FREE");
2382 (void) snprintf(blkbuf + strlen(blkbuf),
2383 buflen - strlen(blkbuf),
2384 " cksum=%016llx:%016llx:%016llx:%016llx",
2385 (u_longlong_t)bp->blk_cksum.zc_word[0],
2386 (u_longlong_t)bp->blk_cksum.zc_word[1],
2387 (u_longlong_t)bp->blk_cksum.zc_word[2],
2388 (u_longlong_t)bp->blk_cksum.zc_word[3]);
2389 }
2390 }
2391
2392 static void
2393 print_indirect(spa_t *spa, blkptr_t *bp, const zbookmark_phys_t *zb,
2394 const dnode_phys_t *dnp)
2395 {
2396 char blkbuf[BP_SPRINTF_LEN];
2397 int l;
2398
2399 if (!BP_IS_EMBEDDED(bp)) {
2400 ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
2401 ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
2402 }
2403
2404 (void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
2405
2406 ASSERT(zb->zb_level >= 0);
2407
2408 for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
2409 if (l == zb->zb_level) {
2410 (void) printf("L%llx", (u_longlong_t)zb->zb_level);
2411 } else {
2412 (void) printf(" ");
2413 }
2414 }
2415
2416 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp, B_FALSE);
2417 if (dump_opt['Z'] && BP_GET_COMPRESS(bp) == ZIO_COMPRESS_ZSTD)
2418 snprintf_zstd_header(spa, blkbuf, sizeof (blkbuf), bp);
2419 (void) printf("%s\n", blkbuf);
2420 }
2421
2422 static int
2423 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
2424 blkptr_t *bp, const zbookmark_phys_t *zb)
2425 {
2426 int err = 0;
2427
2428 if (bp->blk_birth == 0)
2429 return (0);
2430
2431 print_indirect(spa, bp, zb, dnp);
2432
2433 if (BP_GET_LEVEL(bp) > 0 && !BP_IS_HOLE(bp)) {
2434 arc_flags_t flags = ARC_FLAG_WAIT;
2435 int i;
2436 blkptr_t *cbp;
2437 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
2438 arc_buf_t *buf;
2439 uint64_t fill = 0;
2440 ASSERT(!BP_IS_REDACTED(bp));
2441
2442 err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
2443 ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
2444 if (err)
2445 return (err);
2446 ASSERT(buf->b_data);
2447
2448 /* recursively visit blocks below this */
2449 cbp = buf->b_data;
2450 for (i = 0; i < epb; i++, cbp++) {
2451 zbookmark_phys_t czb;
2452
2453 SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
2454 zb->zb_level - 1,
2455 zb->zb_blkid * epb + i);
2456 err = visit_indirect(spa, dnp, cbp, &czb);
2457 if (err)
2458 break;
2459 fill += BP_GET_FILL(cbp);
2460 }
2461 if (!err)
2462 ASSERT3U(fill, ==, BP_GET_FILL(bp));
2463 arc_buf_destroy(buf, &buf);
2464 }
2465
2466 return (err);
2467 }
2468
2469 static void
2470 dump_indirect(dnode_t *dn)
2471 {
2472 dnode_phys_t *dnp = dn->dn_phys;
2473 zbookmark_phys_t czb;
2474
2475 (void) printf("Indirect blocks:\n");
2476
2477 SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
2478 dn->dn_object, dnp->dn_nlevels - 1, 0);
2479 for (int j = 0; j < dnp->dn_nblkptr; j++) {
2480 czb.zb_blkid = j;
2481 (void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
2482 &dnp->dn_blkptr[j], &czb);
2483 }
2484
2485 (void) printf("\n");
2486 }
2487
2488 static void
2489 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
2490 {
2491 (void) os, (void) object;
2492 dsl_dir_phys_t *dd = data;
2493 time_t crtime;
2494 char nice[32];
2495
2496 /* make sure nicenum has enough space */
2497 _Static_assert(sizeof (nice) >= NN_NUMBUF_SZ, "nice truncated");
2498
2499 if (dd == NULL)
2500 return;
2501
2502 ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
2503
2504 crtime = dd->dd_creation_time;
2505 (void) printf("\t\tcreation_time = %s", ctime(&crtime));
2506 (void) printf("\t\thead_dataset_obj = %llu\n",
2507 (u_longlong_t)dd->dd_head_dataset_obj);
2508 (void) printf("\t\tparent_dir_obj = %llu\n",
2509 (u_longlong_t)dd->dd_parent_obj);
2510 (void) printf("\t\torigin_obj = %llu\n",
2511 (u_longlong_t)dd->dd_origin_obj);
2512 (void) printf("\t\tchild_dir_zapobj = %llu\n",
2513 (u_longlong_t)dd->dd_child_dir_zapobj);
2514 zdb_nicenum(dd->dd_used_bytes, nice, sizeof (nice));
2515 (void) printf("\t\tused_bytes = %s\n", nice);
2516 zdb_nicenum(dd->dd_compressed_bytes, nice, sizeof (nice));
2517 (void) printf("\t\tcompressed_bytes = %s\n", nice);
2518 zdb_nicenum(dd->dd_uncompressed_bytes, nice, sizeof (nice));
2519 (void) printf("\t\tuncompressed_bytes = %s\n", nice);
2520 zdb_nicenum(dd->dd_quota, nice, sizeof (nice));
2521 (void) printf("\t\tquota = %s\n", nice);
2522 zdb_nicenum(dd->dd_reserved, nice, sizeof (nice));
2523 (void) printf("\t\treserved = %s\n", nice);
2524 (void) printf("\t\tprops_zapobj = %llu\n",
2525 (u_longlong_t)dd->dd_props_zapobj);
2526 (void) printf("\t\tdeleg_zapobj = %llu\n",
2527 (u_longlong_t)dd->dd_deleg_zapobj);
2528 (void) printf("\t\tflags = %llx\n",
2529 (u_longlong_t)dd->dd_flags);
2530
2531 #define DO(which) \
2532 zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice, \
2533 sizeof (nice)); \
2534 (void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
2535 DO(HEAD);
2536 DO(SNAP);
2537 DO(CHILD);
2538 DO(CHILD_RSRV);
2539 DO(REFRSRV);
2540 #undef DO
2541 (void) printf("\t\tclones = %llu\n",
2542 (u_longlong_t)dd->dd_clones);
2543 }
2544
2545 static void
2546 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
2547 {
2548 (void) os, (void) object;
2549 dsl_dataset_phys_t *ds = data;
2550 time_t crtime;
2551 char used[32], compressed[32], uncompressed[32], unique[32];
2552 char blkbuf[BP_SPRINTF_LEN];
2553
2554 /* make sure nicenum has enough space */
2555 _Static_assert(sizeof (used) >= NN_NUMBUF_SZ, "used truncated");
2556 _Static_assert(sizeof (compressed) >= NN_NUMBUF_SZ,
2557 "compressed truncated");
2558 _Static_assert(sizeof (uncompressed) >= NN_NUMBUF_SZ,
2559 "uncompressed truncated");
2560 _Static_assert(sizeof (unique) >= NN_NUMBUF_SZ, "unique truncated");
2561
2562 if (ds == NULL)
2563 return;
2564
2565 ASSERT(size == sizeof (*ds));
2566 crtime = ds->ds_creation_time;
2567 zdb_nicenum(ds->ds_referenced_bytes, used, sizeof (used));
2568 zdb_nicenum(ds->ds_compressed_bytes, compressed, sizeof (compressed));
2569 zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed,
2570 sizeof (uncompressed));
2571 zdb_nicenum(ds->ds_unique_bytes, unique, sizeof (unique));
2572 snprintf_blkptr(blkbuf, sizeof (blkbuf), &ds->ds_bp);
2573
2574 (void) printf("\t\tdir_obj = %llu\n",
2575 (u_longlong_t)ds->ds_dir_obj);
2576 (void) printf("\t\tprev_snap_obj = %llu\n",
2577 (u_longlong_t)ds->ds_prev_snap_obj);
2578 (void) printf("\t\tprev_snap_txg = %llu\n",
2579 (u_longlong_t)ds->ds_prev_snap_txg);
2580 (void) printf("\t\tnext_snap_obj = %llu\n",
2581 (u_longlong_t)ds->ds_next_snap_obj);
2582 (void) printf("\t\tsnapnames_zapobj = %llu\n",
2583 (u_longlong_t)ds->ds_snapnames_zapobj);
2584 (void) printf("\t\tnum_children = %llu\n",
2585 (u_longlong_t)ds->ds_num_children);
2586 (void) printf("\t\tuserrefs_obj = %llu\n",
2587 (u_longlong_t)ds->ds_userrefs_obj);
2588 (void) printf("\t\tcreation_time = %s", ctime(&crtime));
2589 (void) printf("\t\tcreation_txg = %llu\n",
2590 (u_longlong_t)ds->ds_creation_txg);
2591 (void) printf("\t\tdeadlist_obj = %llu\n",
2592 (u_longlong_t)ds->ds_deadlist_obj);
2593 (void) printf("\t\tused_bytes = %s\n", used);
2594 (void) printf("\t\tcompressed_bytes = %s\n", compressed);
2595 (void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
2596 (void) printf("\t\tunique = %s\n", unique);
2597 (void) printf("\t\tfsid_guid = %llu\n",
2598 (u_longlong_t)ds->ds_fsid_guid);
2599 (void) printf("\t\tguid = %llu\n",
2600 (u_longlong_t)ds->ds_guid);
2601 (void) printf("\t\tflags = %llx\n",
2602 (u_longlong_t)ds->ds_flags);
2603 (void) printf("\t\tnext_clones_obj = %llu\n",
2604 (u_longlong_t)ds->ds_next_clones_obj);
2605 (void) printf("\t\tprops_obj = %llu\n",
2606 (u_longlong_t)ds->ds_props_obj);
2607 (void) printf("\t\tbp = %s\n", blkbuf);
2608 }
2609
2610 static int
2611 dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2612 {
2613 (void) arg, (void) tx;
2614 char blkbuf[BP_SPRINTF_LEN];
2615
2616 if (bp->blk_birth != 0) {
2617 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
2618 (void) printf("\t%s\n", blkbuf);
2619 }
2620 return (0);
2621 }
2622
2623 static void
2624 dump_bptree(objset_t *os, uint64_t obj, const char *name)
2625 {
2626 char bytes[32];
2627 bptree_phys_t *bt;
2628 dmu_buf_t *db;
2629
2630 /* make sure nicenum has enough space */
2631 _Static_assert(sizeof (bytes) >= NN_NUMBUF_SZ, "bytes truncated");
2632
2633 if (dump_opt['d'] < 3)
2634 return;
2635
2636 VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
2637 bt = db->db_data;
2638 zdb_nicenum(bt->bt_bytes, bytes, sizeof (bytes));
2639 (void) printf("\n %s: %llu datasets, %s\n",
2640 name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
2641 dmu_buf_rele(db, FTAG);
2642
2643 if (dump_opt['d'] < 5)
2644 return;
2645
2646 (void) printf("\n");
2647
2648 (void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
2649 }
2650
2651 static int
2652 dump_bpobj_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed, dmu_tx_t *tx)
2653 {
2654 (void) arg, (void) tx;
2655 char blkbuf[BP_SPRINTF_LEN];
2656
2657 ASSERT(bp->blk_birth != 0);
2658 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp, bp_freed);
2659 (void) printf("\t%s\n", blkbuf);
2660 return (0);
2661 }
2662
2663 static void
2664 dump_full_bpobj(bpobj_t *bpo, const char *name, int indent)
2665 {
2666 char bytes[32];
2667 char comp[32];
2668 char uncomp[32];
2669 uint64_t i;
2670
2671 /* make sure nicenum has enough space */
2672 _Static_assert(sizeof (bytes) >= NN_NUMBUF_SZ, "bytes truncated");
2673 _Static_assert(sizeof (comp) >= NN_NUMBUF_SZ, "comp truncated");
2674 _Static_assert(sizeof (uncomp) >= NN_NUMBUF_SZ, "uncomp truncated");
2675
2676 if (dump_opt['d'] < 3)
2677 return;
2678
2679 zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes, sizeof (bytes));
2680 if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
2681 zdb_nicenum(bpo->bpo_phys->bpo_comp, comp, sizeof (comp));
2682 zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp, sizeof (uncomp));
2683 if (bpo->bpo_havefreed) {
2684 (void) printf(" %*s: object %llu, %llu local "
2685 "blkptrs, %llu freed, %llu subobjs in object %llu, "
2686 "%s (%s/%s comp)\n",
2687 indent * 8, name,
2688 (u_longlong_t)bpo->bpo_object,
2689 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2690 (u_longlong_t)bpo->bpo_phys->bpo_num_freed,
2691 (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
2692 (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
2693 bytes, comp, uncomp);
2694 } else {
2695 (void) printf(" %*s: object %llu, %llu local "
2696 "blkptrs, %llu subobjs in object %llu, "
2697 "%s (%s/%s comp)\n",
2698 indent * 8, name,
2699 (u_longlong_t)bpo->bpo_object,
2700 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2701 (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
2702 (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
2703 bytes, comp, uncomp);
2704 }
2705
2706 for (i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
2707 uint64_t subobj;
2708 bpobj_t subbpo;
2709 int error;
2710 VERIFY0(dmu_read(bpo->bpo_os,
2711 bpo->bpo_phys->bpo_subobjs,
2712 i * sizeof (subobj), sizeof (subobj), &subobj, 0));
2713 error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
2714 if (error != 0) {
2715 (void) printf("ERROR %u while trying to open "
2716 "subobj id %llu\n",
2717 error, (u_longlong_t)subobj);
2718 continue;
2719 }
2720 dump_full_bpobj(&subbpo, "subobj", indent + 1);
2721 bpobj_close(&subbpo);
2722 }
2723 } else {
2724 if (bpo->bpo_havefreed) {
2725 (void) printf(" %*s: object %llu, %llu blkptrs, "
2726 "%llu freed, %s\n",
2727 indent * 8, name,
2728 (u_longlong_t)bpo->bpo_object,
2729 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2730 (u_longlong_t)bpo->bpo_phys->bpo_num_freed,
2731 bytes);
2732 } else {
2733 (void) printf(" %*s: object %llu, %llu blkptrs, "
2734 "%s\n",
2735 indent * 8, name,
2736 (u_longlong_t)bpo->bpo_object,
2737 (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2738 bytes);
2739 }
2740 }
2741
2742 if (dump_opt['d'] < 5)
2743 return;
2744
2745
2746 if (indent == 0) {
2747 (void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
2748 (void) printf("\n");
2749 }
2750 }
2751
2752 static int
2753 dump_bookmark(dsl_pool_t *dp, char *name, boolean_t print_redact,
2754 boolean_t print_list)
2755 {
2756 int err = 0;
2757 zfs_bookmark_phys_t prop;
2758 objset_t *mos = dp->dp_spa->spa_meta_objset;
2759 err = dsl_bookmark_lookup(dp, name, NULL, &prop);
2760
2761 if (err != 0) {
2762 return (err);
2763 }
2764
2765 (void) printf("\t#%s: ", strchr(name, '#') + 1);
2766 (void) printf("{guid: %llx creation_txg: %llu creation_time: "
2767 "%llu redaction_obj: %llu}\n", (u_longlong_t)prop.zbm_guid,
2768 (u_longlong_t)prop.zbm_creation_txg,
2769 (u_longlong_t)prop.zbm_creation_time,
2770 (u_longlong_t)prop.zbm_redaction_obj);
2771
2772 IMPLY(print_list, print_redact);
2773 if (!print_redact || prop.zbm_redaction_obj == 0)
2774 return (0);
2775
2776 redaction_list_t *rl;
2777 VERIFY0(dsl_redaction_list_hold_obj(dp,
2778 prop.zbm_redaction_obj, FTAG, &rl));
2779
2780 redaction_list_phys_t *rlp = rl->rl_phys;
2781 (void) printf("\tRedacted:\n\t\tProgress: ");
2782 if (rlp->rlp_last_object != UINT64_MAX ||
2783 rlp->rlp_last_blkid != UINT64_MAX) {
2784 (void) printf("%llu %llu (incomplete)\n",
2785 (u_longlong_t)rlp->rlp_last_object,
2786 (u_longlong_t)rlp->rlp_last_blkid);
2787 } else {
2788 (void) printf("complete\n");
2789 }
2790 (void) printf("\t\tSnapshots: [");
2791 for (unsigned int i = 0; i < rlp->rlp_num_snaps; i++) {
2792 if (i > 0)
2793 (void) printf(", ");
2794 (void) printf("%0llu",
2795 (u_longlong_t)rlp->rlp_snaps[i]);
2796 }
2797 (void) printf("]\n\t\tLength: %llu\n",
2798 (u_longlong_t)rlp->rlp_num_entries);
2799
2800 if (!print_list) {
2801 dsl_redaction_list_rele(rl, FTAG);
2802 return (0);
2803 }
2804
2805 if (rlp->rlp_num_entries == 0) {
2806 dsl_redaction_list_rele(rl, FTAG);
2807 (void) printf("\t\tRedaction List: []\n\n");
2808 return (0);
2809 }
2810
2811 redact_block_phys_t *rbp_buf;
2812 uint64_t size;
2813 dmu_object_info_t doi;
2814
2815 VERIFY0(dmu_object_info(mos, prop.zbm_redaction_obj, &doi));
2816 size = doi.doi_max_offset;
2817 rbp_buf = kmem_alloc(size, KM_SLEEP);
2818
2819 err = dmu_read(mos, prop.zbm_redaction_obj, 0, size,
2820 rbp_buf, 0);
2821 if (err != 0) {
2822 dsl_redaction_list_rele(rl, FTAG);
2823 kmem_free(rbp_buf, size);
2824 return (err);
2825 }
2826
2827 (void) printf("\t\tRedaction List: [{object: %llx, offset: "
2828 "%llx, blksz: %x, count: %llx}",
2829 (u_longlong_t)rbp_buf[0].rbp_object,
2830 (u_longlong_t)rbp_buf[0].rbp_blkid,
2831 (uint_t)(redact_block_get_size(&rbp_buf[0])),
2832 (u_longlong_t)redact_block_get_count(&rbp_buf[0]));
2833
2834 for (size_t i = 1; i < rlp->rlp_num_entries; i++) {
2835 (void) printf(",\n\t\t{object: %llx, offset: %llx, "
2836 "blksz: %x, count: %llx}",
2837 (u_longlong_t)rbp_buf[i].rbp_object,
2838 (u_longlong_t)rbp_buf[i].rbp_blkid,
2839 (uint_t)(redact_block_get_size(&rbp_buf[i])),
2840 (u_longlong_t)redact_block_get_count(&rbp_buf[i]));
2841 }
2842 dsl_redaction_list_rele(rl, FTAG);
2843 kmem_free(rbp_buf, size);
2844 (void) printf("]\n\n");
2845 return (0);
2846 }
2847
2848 static void
2849 dump_bookmarks(objset_t *os, int verbosity)
2850 {
2851 zap_cursor_t zc;
2852 zap_attribute_t attr;
2853 dsl_dataset_t *ds = dmu_objset_ds(os);
2854 dsl_pool_t *dp = spa_get_dsl(os->os_spa);
2855 objset_t *mos = os->os_spa->spa_meta_objset;
2856 if (verbosity < 4)
2857 return;
2858 dsl_pool_config_enter(dp, FTAG);
2859
2860 for (zap_cursor_init(&zc, mos, ds->ds_bookmarks_obj);
2861 zap_cursor_retrieve(&zc, &attr) == 0;
2862 zap_cursor_advance(&zc)) {
2863 char osname[ZFS_MAX_DATASET_NAME_LEN];
2864 char buf[ZFS_MAX_DATASET_NAME_LEN];
2865 int len;
2866 dmu_objset_name(os, osname);
2867 len = snprintf(buf, sizeof (buf), "%s#%s", osname,
2868 attr.za_name);
2869 VERIFY3S(len, <, ZFS_MAX_DATASET_NAME_LEN);
2870 (void) dump_bookmark(dp, buf, verbosity >= 5, verbosity >= 6);
2871 }
2872 zap_cursor_fini(&zc);
2873 dsl_pool_config_exit(dp, FTAG);
2874 }
2875
2876 static void
2877 bpobj_count_refd(bpobj_t *bpo)
2878 {
2879 mos_obj_refd(bpo->bpo_object);
2880
2881 if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
2882 mos_obj_refd(bpo->bpo_phys->bpo_subobjs);
2883 for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
2884 uint64_t subobj;
2885 bpobj_t subbpo;
2886 int error;
2887 VERIFY0(dmu_read(bpo->bpo_os,
2888 bpo->bpo_phys->bpo_subobjs,
2889 i * sizeof (subobj), sizeof (subobj), &subobj, 0));
2890 error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
2891 if (error != 0) {
2892 (void) printf("ERROR %u while trying to open "
2893 "subobj id %llu\n",
2894 error, (u_longlong_t)subobj);
2895 continue;
2896 }
2897 bpobj_count_refd(&subbpo);
2898 bpobj_close(&subbpo);
2899 }
2900 }
2901 }
2902
2903 static int
2904 dsl_deadlist_entry_count_refd(void *arg, dsl_deadlist_entry_t *dle)
2905 {
2906 spa_t *spa = arg;
2907 uint64_t empty_bpobj = spa->spa_dsl_pool->dp_empty_bpobj;
2908 if (dle->dle_bpobj.bpo_object != empty_bpobj)
2909 bpobj_count_refd(&dle->dle_bpobj);
2910 return (0);
2911 }
2912
2913 static int
2914 dsl_deadlist_entry_dump(void *arg, dsl_deadlist_entry_t *dle)
2915 {
2916 ASSERT(arg == NULL);
2917 if (dump_opt['d'] >= 5) {
2918 char buf[128];
2919 (void) snprintf(buf, sizeof (buf),
2920 "mintxg %llu -> obj %llu",
2921 (longlong_t)dle->dle_mintxg,
2922 (longlong_t)dle->dle_bpobj.bpo_object);
2923
2924 dump_full_bpobj(&dle->dle_bpobj, buf, 0);
2925 } else {
2926 (void) printf("mintxg %llu -> obj %llu\n",
2927 (longlong_t)dle->dle_mintxg,
2928 (longlong_t)dle->dle_bpobj.bpo_object);
2929 }
2930 return (0);
2931 }
2932
2933 static void
2934 dump_blkptr_list(dsl_deadlist_t *dl, const char *name)
2935 {
2936 char bytes[32];
2937 char comp[32];
2938 char uncomp[32];
2939 char entries[32];
2940 spa_t *spa = dmu_objset_spa(dl->dl_os);
2941 uint64_t empty_bpobj = spa->spa_dsl_pool->dp_empty_bpobj;
2942
2943 if (dl->dl_oldfmt) {
2944 if (dl->dl_bpobj.bpo_object != empty_bpobj)
2945 bpobj_count_refd(&dl->dl_bpobj);
2946 } else {
2947 mos_obj_refd(dl->dl_object);
2948 dsl_deadlist_iterate(dl, dsl_deadlist_entry_count_refd, spa);
2949 }
2950
2951 /* make sure nicenum has enough space */
2952 _Static_assert(sizeof (bytes) >= NN_NUMBUF_SZ, "bytes truncated");
2953 _Static_assert(sizeof (comp) >= NN_NUMBUF_SZ, "comp truncated");
2954 _Static_assert(sizeof (uncomp) >= NN_NUMBUF_SZ, "uncomp truncated");
2955 _Static_assert(sizeof (entries) >= NN_NUMBUF_SZ, "entries truncated");
2956
2957 if (dump_opt['d'] < 3)
2958 return;
2959
2960 if (dl->dl_oldfmt) {
2961 dump_full_bpobj(&dl->dl_bpobj, "old-format deadlist", 0);
2962 return;
2963 }
2964
2965 zdb_nicenum(dl->dl_phys->dl_used, bytes, sizeof (bytes));
2966 zdb_nicenum(dl->dl_phys->dl_comp, comp, sizeof (comp));
2967 zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp, sizeof (uncomp));
2968 zdb_nicenum(avl_numnodes(&dl->dl_tree), entries, sizeof (entries));
2969 (void) printf("\n %s: %s (%s/%s comp), %s entries\n",
2970 name, bytes, comp, uncomp, entries);
2971
2972 if (dump_opt['d'] < 4)
2973 return;
2974
2975 (void) putchar('\n');
2976
2977 dsl_deadlist_iterate(dl, dsl_deadlist_entry_dump, NULL);
2978 }
2979
2980 static int
2981 verify_dd_livelist(objset_t *os)
2982 {
2983 uint64_t ll_used, used, ll_comp, comp, ll_uncomp, uncomp;
2984 dsl_pool_t *dp = spa_get_dsl(os->os_spa);
2985 dsl_dir_t *dd = os->os_dsl_dataset->ds_dir;
2986
2987 ASSERT(!dmu_objset_is_snapshot(os));
2988 if (!dsl_deadlist_is_open(&dd->dd_livelist))
2989 return (0);
2990
2991 /* Iterate through the livelist to check for duplicates */
2992 dsl_deadlist_iterate(&dd->dd_livelist, sublivelist_verify_lightweight,
2993 NULL);
2994
2995 dsl_pool_config_enter(dp, FTAG);
2996 dsl_deadlist_space(&dd->dd_livelist, &ll_used,
2997 &ll_comp, &ll_uncomp);
2998
2999 dsl_dataset_t *origin_ds;
3000 ASSERT(dsl_pool_config_held(dp));
3001 VERIFY0(dsl_dataset_hold_obj(dp,
3002 dsl_dir_phys(dd)->dd_origin_obj, FTAG, &origin_ds));
3003 VERIFY0(dsl_dataset_space_written(origin_ds, os->os_dsl_dataset,
3004 &used, &comp, &uncomp));
3005 dsl_dataset_rele(origin_ds, FTAG);
3006 dsl_pool_config_exit(dp, FTAG);
3007 /*
3008 * It's possible that the dataset's uncomp space is larger than the
3009 * livelist's because livelists do not track embedded block pointers
3010 */
3011 if (used != ll_used || comp != ll_comp || uncomp < ll_uncomp) {
3012 char nice_used[32], nice_comp[32], nice_uncomp[32];
3013 (void) printf("Discrepancy in space accounting:\n");
3014 zdb_nicenum(used, nice_used, sizeof (nice_used));
3015 zdb_nicenum(comp, nice_comp, sizeof (nice_comp));
3016 zdb_nicenum(uncomp, nice_uncomp, sizeof (nice_uncomp));
3017 (void) printf("dir: used %s, comp %s, uncomp %s\n",
3018 nice_used, nice_comp, nice_uncomp);
3019 zdb_nicenum(ll_used, nice_used, sizeof (nice_used));
3020 zdb_nicenum(ll_comp, nice_comp, sizeof (nice_comp));
3021 zdb_nicenum(ll_uncomp, nice_uncomp, sizeof (nice_uncomp));
3022 (void) printf("livelist: used %s, comp %s, uncomp %s\n",
3023 nice_used, nice_comp, nice_uncomp);
3024 return (1);
3025 }
3026 return (0);
3027 }
3028
3029 static char *key_material = NULL;
3030
3031 static boolean_t
3032 zdb_derive_key(dsl_dir_t *dd, uint8_t *key_out)
3033 {
3034 uint64_t keyformat, salt, iters;
3035 int i;
3036 unsigned char c;
3037
3038 VERIFY0(zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
3039 zfs_prop_to_name(ZFS_PROP_KEYFORMAT), sizeof (uint64_t),
3040 1, &keyformat));
3041
3042 switch (keyformat) {
3043 case ZFS_KEYFORMAT_HEX:
3044 for (i = 0; i < WRAPPING_KEY_LEN * 2; i += 2) {
3045 if (!isxdigit(key_material[i]) ||
3046 !isxdigit(key_material[i+1]))
3047 return (B_FALSE);
3048 if (sscanf(&key_material[i], "%02hhx", &c) != 1)
3049 return (B_FALSE);
3050 key_out[i / 2] = c;
3051 }
3052 break;
3053
3054 case ZFS_KEYFORMAT_PASSPHRASE:
3055 VERIFY0(zap_lookup(dd->dd_pool->dp_meta_objset,
3056 dd->dd_crypto_obj, zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT),
3057 sizeof (uint64_t), 1, &salt));
3058 VERIFY0(zap_lookup(dd->dd_pool->dp_meta_objset,
3059 dd->dd_crypto_obj, zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS),
3060 sizeof (uint64_t), 1, &iters));
3061
3062 if (PKCS5_PBKDF2_HMAC_SHA1(key_material, strlen(key_material),
3063 ((uint8_t *)&salt), sizeof (uint64_t), iters,
3064 WRAPPING_KEY_LEN, key_out) != 1)
3065 return (B_FALSE);
3066
3067 break;
3068
3069 default:
3070 fatal("no support for key format %u\n",
3071 (unsigned int) keyformat);
3072 }
3073
3074 return (B_TRUE);
3075 }
3076
3077 static char encroot[ZFS_MAX_DATASET_NAME_LEN];
3078 static boolean_t key_loaded = B_FALSE;
3079
3080 static void
3081 zdb_load_key(objset_t *os)
3082 {
3083 dsl_pool_t *dp;
3084 dsl_dir_t *dd, *rdd;
3085 uint8_t key[WRAPPING_KEY_LEN];
3086 uint64_t rddobj;
3087 int err;
3088
3089 dp = spa_get_dsl(os->os_spa);
3090 dd = os->os_dsl_dataset->ds_dir;
3091
3092 dsl_pool_config_enter(dp, FTAG);
3093 VERIFY0(zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
3094 DSL_CRYPTO_KEY_ROOT_DDOBJ, sizeof (uint64_t), 1, &rddobj));
3095 VERIFY0(dsl_dir_hold_obj(dd->dd_pool, rddobj, NULL, FTAG, &rdd));
3096 dsl_dir_name(rdd, encroot);
3097 dsl_dir_rele(rdd, FTAG);
3098
3099 if (!zdb_derive_key(dd, key))
3100 fatal("couldn't derive encryption key");
3101
3102 dsl_pool_config_exit(dp, FTAG);
3103
3104 ASSERT3U(dsl_dataset_get_keystatus(dd), ==, ZFS_KEYSTATUS_UNAVAILABLE);
3105
3106 dsl_crypto_params_t *dcp;
3107 nvlist_t *crypto_args;
3108
3109 crypto_args = fnvlist_alloc();
3110 fnvlist_add_uint8_array(crypto_args, "wkeydata",
3111 (uint8_t *)key, WRAPPING_KEY_LEN);
3112 VERIFY0(dsl_crypto_params_create_nvlist(DCP_CMD_NONE,
3113 NULL, crypto_args, &dcp));
3114 err = spa_keystore_load_wkey(encroot, dcp, B_FALSE);
3115
3116 dsl_crypto_params_free(dcp, (err != 0));
3117 fnvlist_free(crypto_args);
3118
3119 if (err != 0)
3120 fatal(
3121 "couldn't load encryption key for %s: %s",
3122 encroot, err == ZFS_ERR_CRYPTO_NOTSUP ?
3123 "crypto params not supported" : 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 = 2ULL << SPA_MAXBLOCKSHIFT;
8812 zfs_arc_max = 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 }