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