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