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