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