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