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