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