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