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