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