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