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