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