xref: /freebsd/sys/contrib/openzfs/cmd/zdb/zdb.c (revision 7c43148a974877188a930e4078a164f83da8e652)
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 
4138 	(void) printf("\traidz_reflow state=%u off=%llu\n",
4139 	    (int)RRSS_GET_STATE(ub),
4140 	    (u_longlong_t)RRSS_GET_OFFSET(ub));
4141 
4142 	(void) printf("%s", footer ? footer : "");
4143 }
4144 
4145 static void
4146 dump_config(spa_t *spa)
4147 {
4148 	dmu_buf_t *db;
4149 	size_t nvsize = 0;
4150 	int error = 0;
4151 
4152 
4153 	error = dmu_bonus_hold(spa->spa_meta_objset,
4154 	    spa->spa_config_object, FTAG, &db);
4155 
4156 	if (error == 0) {
4157 		nvsize = *(uint64_t *)db->db_data;
4158 		dmu_buf_rele(db, FTAG);
4159 
4160 		(void) printf("\nMOS Configuration:\n");
4161 		dump_packed_nvlist(spa->spa_meta_objset,
4162 		    spa->spa_config_object, (void *)&nvsize, 1);
4163 	} else {
4164 		(void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
4165 		    (u_longlong_t)spa->spa_config_object, error);
4166 	}
4167 }
4168 
4169 static void
4170 dump_cachefile(const char *cachefile)
4171 {
4172 	int fd;
4173 	struct stat64 statbuf;
4174 	char *buf;
4175 	nvlist_t *config;
4176 
4177 	if ((fd = open64(cachefile, O_RDONLY)) < 0) {
4178 		(void) printf("cannot open '%s': %s\n", cachefile,
4179 		    strerror(errno));
4180 		exit(1);
4181 	}
4182 
4183 	if (fstat64(fd, &statbuf) != 0) {
4184 		(void) printf("failed to stat '%s': %s\n", cachefile,
4185 		    strerror(errno));
4186 		exit(1);
4187 	}
4188 
4189 	if ((buf = malloc(statbuf.st_size)) == NULL) {
4190 		(void) fprintf(stderr, "failed to allocate %llu bytes\n",
4191 		    (u_longlong_t)statbuf.st_size);
4192 		exit(1);
4193 	}
4194 
4195 	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
4196 		(void) fprintf(stderr, "failed to read %llu bytes\n",
4197 		    (u_longlong_t)statbuf.st_size);
4198 		exit(1);
4199 	}
4200 
4201 	(void) close(fd);
4202 
4203 	if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
4204 		(void) fprintf(stderr, "failed to unpack nvlist\n");
4205 		exit(1);
4206 	}
4207 
4208 	free(buf);
4209 
4210 	dump_nvlist(config, 0);
4211 
4212 	nvlist_free(config);
4213 }
4214 
4215 /*
4216  * ZFS label nvlist stats
4217  */
4218 typedef struct zdb_nvl_stats {
4219 	int		zns_list_count;
4220 	int		zns_leaf_count;
4221 	size_t		zns_leaf_largest;
4222 	size_t		zns_leaf_total;
4223 	nvlist_t	*zns_string;
4224 	nvlist_t	*zns_uint64;
4225 	nvlist_t	*zns_boolean;
4226 } zdb_nvl_stats_t;
4227 
4228 static void
4229 collect_nvlist_stats(nvlist_t *nvl, zdb_nvl_stats_t *stats)
4230 {
4231 	nvlist_t *list, **array;
4232 	nvpair_t *nvp = NULL;
4233 	const char *name;
4234 	uint_t i, items;
4235 
4236 	stats->zns_list_count++;
4237 
4238 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4239 		name = nvpair_name(nvp);
4240 
4241 		switch (nvpair_type(nvp)) {
4242 		case DATA_TYPE_STRING:
4243 			fnvlist_add_string(stats->zns_string, name,
4244 			    fnvpair_value_string(nvp));
4245 			break;
4246 		case DATA_TYPE_UINT64:
4247 			fnvlist_add_uint64(stats->zns_uint64, name,
4248 			    fnvpair_value_uint64(nvp));
4249 			break;
4250 		case DATA_TYPE_BOOLEAN:
4251 			fnvlist_add_boolean(stats->zns_boolean, name);
4252 			break;
4253 		case DATA_TYPE_NVLIST:
4254 			if (nvpair_value_nvlist(nvp, &list) == 0)
4255 				collect_nvlist_stats(list, stats);
4256 			break;
4257 		case DATA_TYPE_NVLIST_ARRAY:
4258 			if (nvpair_value_nvlist_array(nvp, &array, &items) != 0)
4259 				break;
4260 
4261 			for (i = 0; i < items; i++) {
4262 				collect_nvlist_stats(array[i], stats);
4263 
4264 				/* collect stats on leaf vdev */
4265 				if (strcmp(name, "children") == 0) {
4266 					size_t size;
4267 
4268 					(void) nvlist_size(array[i], &size,
4269 					    NV_ENCODE_XDR);
4270 					stats->zns_leaf_total += size;
4271 					if (size > stats->zns_leaf_largest)
4272 						stats->zns_leaf_largest = size;
4273 					stats->zns_leaf_count++;
4274 				}
4275 			}
4276 			break;
4277 		default:
4278 			(void) printf("skip type %d!\n", (int)nvpair_type(nvp));
4279 		}
4280 	}
4281 }
4282 
4283 static void
4284 dump_nvlist_stats(nvlist_t *nvl, size_t cap)
4285 {
4286 	zdb_nvl_stats_t stats = { 0 };
4287 	size_t size, sum = 0, total;
4288 	size_t noise;
4289 
4290 	/* requires nvlist with non-unique names for stat collection */
4291 	VERIFY0(nvlist_alloc(&stats.zns_string, 0, 0));
4292 	VERIFY0(nvlist_alloc(&stats.zns_uint64, 0, 0));
4293 	VERIFY0(nvlist_alloc(&stats.zns_boolean, 0, 0));
4294 	VERIFY0(nvlist_size(stats.zns_boolean, &noise, NV_ENCODE_XDR));
4295 
4296 	(void) printf("\n\nZFS Label NVList Config Stats:\n");
4297 
4298 	VERIFY0(nvlist_size(nvl, &total, NV_ENCODE_XDR));
4299 	(void) printf("  %d bytes used, %d bytes free (using %4.1f%%)\n\n",
4300 	    (int)total, (int)(cap - total), 100.0 * total / cap);
4301 
4302 	collect_nvlist_stats(nvl, &stats);
4303 
4304 	VERIFY0(nvlist_size(stats.zns_uint64, &size, NV_ENCODE_XDR));
4305 	size -= noise;
4306 	sum += size;
4307 	(void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "integers:",
4308 	    (int)fnvlist_num_pairs(stats.zns_uint64),
4309 	    (int)size, 100.0 * size / total);
4310 
4311 	VERIFY0(nvlist_size(stats.zns_string, &size, NV_ENCODE_XDR));
4312 	size -= noise;
4313 	sum += size;
4314 	(void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "strings:",
4315 	    (int)fnvlist_num_pairs(stats.zns_string),
4316 	    (int)size, 100.0 * size / total);
4317 
4318 	VERIFY0(nvlist_size(stats.zns_boolean, &size, NV_ENCODE_XDR));
4319 	size -= noise;
4320 	sum += size;
4321 	(void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "booleans:",
4322 	    (int)fnvlist_num_pairs(stats.zns_boolean),
4323 	    (int)size, 100.0 * size / total);
4324 
4325 	size = total - sum;	/* treat remainder as nvlist overhead */
4326 	(void) printf("%12s %4d %6d bytes (%5.2f%%)\n\n", "nvlists:",
4327 	    stats.zns_list_count, (int)size, 100.0 * size / total);
4328 
4329 	if (stats.zns_leaf_count > 0) {
4330 		size_t average = stats.zns_leaf_total / stats.zns_leaf_count;
4331 
4332 		(void) printf("%12s %4d %6d bytes average\n", "leaf vdevs:",
4333 		    stats.zns_leaf_count, (int)average);
4334 		(void) printf("%24d bytes largest\n",
4335 		    (int)stats.zns_leaf_largest);
4336 
4337 		if (dump_opt['l'] >= 3 && average > 0)
4338 			(void) printf("  space for %d additional leaf vdevs\n",
4339 			    (int)((cap - total) / average));
4340 	}
4341 	(void) printf("\n");
4342 
4343 	nvlist_free(stats.zns_string);
4344 	nvlist_free(stats.zns_uint64);
4345 	nvlist_free(stats.zns_boolean);
4346 }
4347 
4348 typedef struct cksum_record {
4349 	zio_cksum_t cksum;
4350 	boolean_t labels[VDEV_LABELS];
4351 	avl_node_t link;
4352 } cksum_record_t;
4353 
4354 static int
4355 cksum_record_compare(const void *x1, const void *x2)
4356 {
4357 	const cksum_record_t *l = (cksum_record_t *)x1;
4358 	const cksum_record_t *r = (cksum_record_t *)x2;
4359 	int arraysize = ARRAY_SIZE(l->cksum.zc_word);
4360 	int difference = 0;
4361 
4362 	for (int i = 0; i < arraysize; i++) {
4363 		difference = TREE_CMP(l->cksum.zc_word[i], r->cksum.zc_word[i]);
4364 		if (difference)
4365 			break;
4366 	}
4367 
4368 	return (difference);
4369 }
4370 
4371 static cksum_record_t *
4372 cksum_record_alloc(zio_cksum_t *cksum, int l)
4373 {
4374 	cksum_record_t *rec;
4375 
4376 	rec = umem_zalloc(sizeof (*rec), UMEM_NOFAIL);
4377 	rec->cksum = *cksum;
4378 	rec->labels[l] = B_TRUE;
4379 
4380 	return (rec);
4381 }
4382 
4383 static cksum_record_t *
4384 cksum_record_lookup(avl_tree_t *tree, zio_cksum_t *cksum)
4385 {
4386 	cksum_record_t lookup = { .cksum = *cksum };
4387 	avl_index_t where;
4388 
4389 	return (avl_find(tree, &lookup, &where));
4390 }
4391 
4392 static cksum_record_t *
4393 cksum_record_insert(avl_tree_t *tree, zio_cksum_t *cksum, int l)
4394 {
4395 	cksum_record_t *rec;
4396 
4397 	rec = cksum_record_lookup(tree, cksum);
4398 	if (rec) {
4399 		rec->labels[l] = B_TRUE;
4400 	} else {
4401 		rec = cksum_record_alloc(cksum, l);
4402 		avl_add(tree, rec);
4403 	}
4404 
4405 	return (rec);
4406 }
4407 
4408 static int
4409 first_label(cksum_record_t *rec)
4410 {
4411 	for (int i = 0; i < VDEV_LABELS; i++)
4412 		if (rec->labels[i])
4413 			return (i);
4414 
4415 	return (-1);
4416 }
4417 
4418 static void
4419 print_label_numbers(const char *prefix, const cksum_record_t *rec)
4420 {
4421 	fputs(prefix, stdout);
4422 	for (int i = 0; i < VDEV_LABELS; i++)
4423 		if (rec->labels[i] == B_TRUE)
4424 			printf("%d ", i);
4425 	putchar('\n');
4426 }
4427 
4428 #define	MAX_UBERBLOCK_COUNT (VDEV_UBERBLOCK_RING >> UBERBLOCK_SHIFT)
4429 
4430 typedef struct zdb_label {
4431 	vdev_label_t label;
4432 	uint64_t label_offset;
4433 	nvlist_t *config_nv;
4434 	cksum_record_t *config;
4435 	cksum_record_t *uberblocks[MAX_UBERBLOCK_COUNT];
4436 	boolean_t header_printed;
4437 	boolean_t read_failed;
4438 	boolean_t cksum_valid;
4439 } zdb_label_t;
4440 
4441 static void
4442 print_label_header(zdb_label_t *label, int l)
4443 {
4444 
4445 	if (dump_opt['q'])
4446 		return;
4447 
4448 	if (label->header_printed == B_TRUE)
4449 		return;
4450 
4451 	(void) printf("------------------------------------\n");
4452 	(void) printf("LABEL %d %s\n", l,
4453 	    label->cksum_valid ? "" : "(Bad label cksum)");
4454 	(void) printf("------------------------------------\n");
4455 
4456 	label->header_printed = B_TRUE;
4457 }
4458 
4459 static void
4460 print_l2arc_header(void)
4461 {
4462 	(void) printf("------------------------------------\n");
4463 	(void) printf("L2ARC device header\n");
4464 	(void) printf("------------------------------------\n");
4465 }
4466 
4467 static void
4468 print_l2arc_log_blocks(void)
4469 {
4470 	(void) printf("------------------------------------\n");
4471 	(void) printf("L2ARC device log blocks\n");
4472 	(void) printf("------------------------------------\n");
4473 }
4474 
4475 static void
4476 dump_l2arc_log_entries(uint64_t log_entries,
4477     l2arc_log_ent_phys_t *le, uint64_t i)
4478 {
4479 	for (int j = 0; j < log_entries; j++) {
4480 		dva_t dva = le[j].le_dva;
4481 		(void) printf("lb[%4llu]\tle[%4d]\tDVA asize: %llu, "
4482 		    "vdev: %llu, offset: %llu\n",
4483 		    (u_longlong_t)i, j + 1,
4484 		    (u_longlong_t)DVA_GET_ASIZE(&dva),
4485 		    (u_longlong_t)DVA_GET_VDEV(&dva),
4486 		    (u_longlong_t)DVA_GET_OFFSET(&dva));
4487 		(void) printf("|\t\t\t\tbirth: %llu\n",
4488 		    (u_longlong_t)le[j].le_birth);
4489 		(void) printf("|\t\t\t\tlsize: %llu\n",
4490 		    (u_longlong_t)L2BLK_GET_LSIZE((&le[j])->le_prop));
4491 		(void) printf("|\t\t\t\tpsize: %llu\n",
4492 		    (u_longlong_t)L2BLK_GET_PSIZE((&le[j])->le_prop));
4493 		(void) printf("|\t\t\t\tcompr: %llu\n",
4494 		    (u_longlong_t)L2BLK_GET_COMPRESS((&le[j])->le_prop));
4495 		(void) printf("|\t\t\t\tcomplevel: %llu\n",
4496 		    (u_longlong_t)(&le[j])->le_complevel);
4497 		(void) printf("|\t\t\t\ttype: %llu\n",
4498 		    (u_longlong_t)L2BLK_GET_TYPE((&le[j])->le_prop));
4499 		(void) printf("|\t\t\t\tprotected: %llu\n",
4500 		    (u_longlong_t)L2BLK_GET_PROTECTED((&le[j])->le_prop));
4501 		(void) printf("|\t\t\t\tprefetch: %llu\n",
4502 		    (u_longlong_t)L2BLK_GET_PREFETCH((&le[j])->le_prop));
4503 		(void) printf("|\t\t\t\taddress: %llu\n",
4504 		    (u_longlong_t)le[j].le_daddr);
4505 		(void) printf("|\t\t\t\tARC state: %llu\n",
4506 		    (u_longlong_t)L2BLK_GET_STATE((&le[j])->le_prop));
4507 		(void) printf("|\n");
4508 	}
4509 	(void) printf("\n");
4510 }
4511 
4512 static void
4513 dump_l2arc_log_blkptr(const l2arc_log_blkptr_t *lbps)
4514 {
4515 	(void) printf("|\t\tdaddr: %llu\n", (u_longlong_t)lbps->lbp_daddr);
4516 	(void) printf("|\t\tpayload_asize: %llu\n",
4517 	    (u_longlong_t)lbps->lbp_payload_asize);
4518 	(void) printf("|\t\tpayload_start: %llu\n",
4519 	    (u_longlong_t)lbps->lbp_payload_start);
4520 	(void) printf("|\t\tlsize: %llu\n",
4521 	    (u_longlong_t)L2BLK_GET_LSIZE(lbps->lbp_prop));
4522 	(void) printf("|\t\tasize: %llu\n",
4523 	    (u_longlong_t)L2BLK_GET_PSIZE(lbps->lbp_prop));
4524 	(void) printf("|\t\tcompralgo: %llu\n",
4525 	    (u_longlong_t)L2BLK_GET_COMPRESS(lbps->lbp_prop));
4526 	(void) printf("|\t\tcksumalgo: %llu\n",
4527 	    (u_longlong_t)L2BLK_GET_CHECKSUM(lbps->lbp_prop));
4528 	(void) printf("|\n\n");
4529 }
4530 
4531 static void
4532 dump_l2arc_log_blocks(int fd, const l2arc_dev_hdr_phys_t *l2dhdr,
4533     l2arc_dev_hdr_phys_t *rebuild)
4534 {
4535 	l2arc_log_blk_phys_t this_lb;
4536 	uint64_t asize;
4537 	l2arc_log_blkptr_t lbps[2];
4538 	abd_t *abd;
4539 	zio_cksum_t cksum;
4540 	int failed = 0;
4541 	l2arc_dev_t dev;
4542 
4543 	if (!dump_opt['q'])
4544 		print_l2arc_log_blocks();
4545 	memcpy(lbps, l2dhdr->dh_start_lbps, sizeof (lbps));
4546 
4547 	dev.l2ad_evict = l2dhdr->dh_evict;
4548 	dev.l2ad_start = l2dhdr->dh_start;
4549 	dev.l2ad_end = l2dhdr->dh_end;
4550 
4551 	if (l2dhdr->dh_start_lbps[0].lbp_daddr == 0) {
4552 		/* no log blocks to read */
4553 		if (!dump_opt['q']) {
4554 			(void) printf("No log blocks to read\n");
4555 			(void) printf("\n");
4556 		}
4557 		return;
4558 	} else {
4559 		dev.l2ad_hand = lbps[0].lbp_daddr +
4560 		    L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
4561 	}
4562 
4563 	dev.l2ad_first = !!(l2dhdr->dh_flags & L2ARC_DEV_HDR_EVICT_FIRST);
4564 
4565 	for (;;) {
4566 		if (!l2arc_log_blkptr_valid(&dev, &lbps[0]))
4567 			break;
4568 
4569 		/* L2BLK_GET_PSIZE returns aligned size for log blocks */
4570 		asize = L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
4571 		if (pread64(fd, &this_lb, asize, lbps[0].lbp_daddr) != asize) {
4572 			if (!dump_opt['q']) {
4573 				(void) printf("Error while reading next log "
4574 				    "block\n\n");
4575 			}
4576 			break;
4577 		}
4578 
4579 		fletcher_4_native_varsize(&this_lb, asize, &cksum);
4580 		if (!ZIO_CHECKSUM_EQUAL(cksum, lbps[0].lbp_cksum)) {
4581 			failed++;
4582 			if (!dump_opt['q']) {
4583 				(void) printf("Invalid cksum\n");
4584 				dump_l2arc_log_blkptr(&lbps[0]);
4585 			}
4586 			break;
4587 		}
4588 
4589 		switch (L2BLK_GET_COMPRESS((&lbps[0])->lbp_prop)) {
4590 		case ZIO_COMPRESS_OFF:
4591 			break;
4592 		default:
4593 			abd = abd_alloc_for_io(asize, B_TRUE);
4594 			abd_copy_from_buf_off(abd, &this_lb, 0, asize);
4595 			if (zio_decompress_data(L2BLK_GET_COMPRESS(
4596 			    (&lbps[0])->lbp_prop), abd, &this_lb,
4597 			    asize, sizeof (this_lb), NULL) != 0) {
4598 				(void) printf("L2ARC block decompression "
4599 				    "failed\n");
4600 				abd_free(abd);
4601 				goto out;
4602 			}
4603 			abd_free(abd);
4604 			break;
4605 		}
4606 
4607 		if (this_lb.lb_magic == BSWAP_64(L2ARC_LOG_BLK_MAGIC))
4608 			byteswap_uint64_array(&this_lb, sizeof (this_lb));
4609 		if (this_lb.lb_magic != L2ARC_LOG_BLK_MAGIC) {
4610 			if (!dump_opt['q'])
4611 				(void) printf("Invalid log block magic\n\n");
4612 			break;
4613 		}
4614 
4615 		rebuild->dh_lb_count++;
4616 		rebuild->dh_lb_asize += asize;
4617 		if (dump_opt['l'] > 1 && !dump_opt['q']) {
4618 			(void) printf("lb[%4llu]\tmagic: %llu\n",
4619 			    (u_longlong_t)rebuild->dh_lb_count,
4620 			    (u_longlong_t)this_lb.lb_magic);
4621 			dump_l2arc_log_blkptr(&lbps[0]);
4622 		}
4623 
4624 		if (dump_opt['l'] > 2 && !dump_opt['q'])
4625 			dump_l2arc_log_entries(l2dhdr->dh_log_entries,
4626 			    this_lb.lb_entries,
4627 			    rebuild->dh_lb_count);
4628 
4629 		if (l2arc_range_check_overlap(lbps[1].lbp_payload_start,
4630 		    lbps[0].lbp_payload_start, dev.l2ad_evict) &&
4631 		    !dev.l2ad_first)
4632 			break;
4633 
4634 		lbps[0] = lbps[1];
4635 		lbps[1] = this_lb.lb_prev_lbp;
4636 	}
4637 out:
4638 	if (!dump_opt['q']) {
4639 		(void) printf("log_blk_count:\t %llu with valid cksum\n",
4640 		    (u_longlong_t)rebuild->dh_lb_count);
4641 		(void) printf("\t\t %d with invalid cksum\n", failed);
4642 		(void) printf("log_blk_asize:\t %llu\n\n",
4643 		    (u_longlong_t)rebuild->dh_lb_asize);
4644 	}
4645 }
4646 
4647 static int
4648 dump_l2arc_header(int fd)
4649 {
4650 	l2arc_dev_hdr_phys_t l2dhdr = {0}, rebuild = {0};
4651 	int error = B_FALSE;
4652 
4653 	if (pread64(fd, &l2dhdr, sizeof (l2dhdr),
4654 	    VDEV_LABEL_START_SIZE) != sizeof (l2dhdr)) {
4655 		error = B_TRUE;
4656 	} else {
4657 		if (l2dhdr.dh_magic == BSWAP_64(L2ARC_DEV_HDR_MAGIC))
4658 			byteswap_uint64_array(&l2dhdr, sizeof (l2dhdr));
4659 
4660 		if (l2dhdr.dh_magic != L2ARC_DEV_HDR_MAGIC)
4661 			error = B_TRUE;
4662 	}
4663 
4664 	if (error) {
4665 		(void) printf("L2ARC device header not found\n\n");
4666 		/* Do not return an error here for backward compatibility */
4667 		return (0);
4668 	} else if (!dump_opt['q']) {
4669 		print_l2arc_header();
4670 
4671 		(void) printf("    magic: %llu\n",
4672 		    (u_longlong_t)l2dhdr.dh_magic);
4673 		(void) printf("    version: %llu\n",
4674 		    (u_longlong_t)l2dhdr.dh_version);
4675 		(void) printf("    pool_guid: %llu\n",
4676 		    (u_longlong_t)l2dhdr.dh_spa_guid);
4677 		(void) printf("    flags: %llu\n",
4678 		    (u_longlong_t)l2dhdr.dh_flags);
4679 		(void) printf("    start_lbps[0]: %llu\n",
4680 		    (u_longlong_t)
4681 		    l2dhdr.dh_start_lbps[0].lbp_daddr);
4682 		(void) printf("    start_lbps[1]: %llu\n",
4683 		    (u_longlong_t)
4684 		    l2dhdr.dh_start_lbps[1].lbp_daddr);
4685 		(void) printf("    log_blk_ent: %llu\n",
4686 		    (u_longlong_t)l2dhdr.dh_log_entries);
4687 		(void) printf("    start: %llu\n",
4688 		    (u_longlong_t)l2dhdr.dh_start);
4689 		(void) printf("    end: %llu\n",
4690 		    (u_longlong_t)l2dhdr.dh_end);
4691 		(void) printf("    evict: %llu\n",
4692 		    (u_longlong_t)l2dhdr.dh_evict);
4693 		(void) printf("    lb_asize_refcount: %llu\n",
4694 		    (u_longlong_t)l2dhdr.dh_lb_asize);
4695 		(void) printf("    lb_count_refcount: %llu\n",
4696 		    (u_longlong_t)l2dhdr.dh_lb_count);
4697 		(void) printf("    trim_action_time: %llu\n",
4698 		    (u_longlong_t)l2dhdr.dh_trim_action_time);
4699 		(void) printf("    trim_state: %llu\n\n",
4700 		    (u_longlong_t)l2dhdr.dh_trim_state);
4701 	}
4702 
4703 	dump_l2arc_log_blocks(fd, &l2dhdr, &rebuild);
4704 	/*
4705 	 * The total aligned size of log blocks and the number of log blocks
4706 	 * reported in the header of the device may be less than what zdb
4707 	 * reports by dump_l2arc_log_blocks() which emulates l2arc_rebuild().
4708 	 * This happens because dump_l2arc_log_blocks() lacks the memory
4709 	 * pressure valve that l2arc_rebuild() has. Thus, if we are on a system
4710 	 * with low memory, l2arc_rebuild will exit prematurely and dh_lb_asize
4711 	 * and dh_lb_count will be lower to begin with than what exists on the
4712 	 * device. This is normal and zdb should not exit with an error. The
4713 	 * opposite case should never happen though, the values reported in the
4714 	 * header should never be higher than what dump_l2arc_log_blocks() and
4715 	 * l2arc_rebuild() report. If this happens there is a leak in the
4716 	 * accounting of log blocks.
4717 	 */
4718 	if (l2dhdr.dh_lb_asize > rebuild.dh_lb_asize ||
4719 	    l2dhdr.dh_lb_count > rebuild.dh_lb_count)
4720 		return (1);
4721 
4722 	return (0);
4723 }
4724 
4725 static void
4726 dump_config_from_label(zdb_label_t *label, size_t buflen, int l)
4727 {
4728 	if (dump_opt['q'])
4729 		return;
4730 
4731 	if ((dump_opt['l'] < 3) && (first_label(label->config) != l))
4732 		return;
4733 
4734 	print_label_header(label, l);
4735 	dump_nvlist(label->config_nv, 4);
4736 	print_label_numbers("    labels = ", label->config);
4737 
4738 	if (dump_opt['l'] >= 2)
4739 		dump_nvlist_stats(label->config_nv, buflen);
4740 }
4741 
4742 #define	ZDB_MAX_UB_HEADER_SIZE 32
4743 
4744 static void
4745 dump_label_uberblocks(zdb_label_t *label, uint64_t ashift, int label_num)
4746 {
4747 
4748 	vdev_t vd;
4749 	char header[ZDB_MAX_UB_HEADER_SIZE];
4750 
4751 	vd.vdev_ashift = ashift;
4752 	vd.vdev_top = &vd;
4753 
4754 	for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
4755 		uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
4756 		uberblock_t *ub = (void *)((char *)&label->label + uoff);
4757 		cksum_record_t *rec = label->uberblocks[i];
4758 
4759 		if (rec == NULL) {
4760 			if (dump_opt['u'] >= 2) {
4761 				print_label_header(label, label_num);
4762 				(void) printf("    Uberblock[%d] invalid\n", i);
4763 			}
4764 			continue;
4765 		}
4766 
4767 		if ((dump_opt['u'] < 3) && (first_label(rec) != label_num))
4768 			continue;
4769 
4770 		if ((dump_opt['u'] < 4) &&
4771 		    (ub->ub_mmp_magic == MMP_MAGIC) && ub->ub_mmp_delay &&
4772 		    (i >= VDEV_UBERBLOCK_COUNT(&vd) - MMP_BLOCKS_PER_LABEL))
4773 			continue;
4774 
4775 		print_label_header(label, label_num);
4776 		(void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
4777 		    "    Uberblock[%d]\n", i);
4778 		dump_uberblock(ub, header, "");
4779 		print_label_numbers("        labels = ", rec);
4780 	}
4781 }
4782 
4783 static char curpath[PATH_MAX];
4784 
4785 /*
4786  * Iterate through the path components, recursively passing
4787  * current one's obj and remaining path until we find the obj
4788  * for the last one.
4789  */
4790 static int
4791 dump_path_impl(objset_t *os, uint64_t obj, char *name, uint64_t *retobj)
4792 {
4793 	int err;
4794 	boolean_t header = B_TRUE;
4795 	uint64_t child_obj;
4796 	char *s;
4797 	dmu_buf_t *db;
4798 	dmu_object_info_t doi;
4799 
4800 	if ((s = strchr(name, '/')) != NULL)
4801 		*s = '\0';
4802 	err = zap_lookup(os, obj, name, 8, 1, &child_obj);
4803 
4804 	(void) strlcat(curpath, name, sizeof (curpath));
4805 
4806 	if (err != 0) {
4807 		(void) fprintf(stderr, "failed to lookup %s: %s\n",
4808 		    curpath, strerror(err));
4809 		return (err);
4810 	}
4811 
4812 	child_obj = ZFS_DIRENT_OBJ(child_obj);
4813 	err = sa_buf_hold(os, child_obj, FTAG, &db);
4814 	if (err != 0) {
4815 		(void) fprintf(stderr,
4816 		    "failed to get SA dbuf for obj %llu: %s\n",
4817 		    (u_longlong_t)child_obj, strerror(err));
4818 		return (EINVAL);
4819 	}
4820 	dmu_object_info_from_db(db, &doi);
4821 	sa_buf_rele(db, FTAG);
4822 
4823 	if (doi.doi_bonus_type != DMU_OT_SA &&
4824 	    doi.doi_bonus_type != DMU_OT_ZNODE) {
4825 		(void) fprintf(stderr, "invalid bonus type %d for obj %llu\n",
4826 		    doi.doi_bonus_type, (u_longlong_t)child_obj);
4827 		return (EINVAL);
4828 	}
4829 
4830 	if (dump_opt['v'] > 6) {
4831 		(void) printf("obj=%llu %s type=%d bonustype=%d\n",
4832 		    (u_longlong_t)child_obj, curpath, doi.doi_type,
4833 		    doi.doi_bonus_type);
4834 	}
4835 
4836 	(void) strlcat(curpath, "/", sizeof (curpath));
4837 
4838 	switch (doi.doi_type) {
4839 	case DMU_OT_DIRECTORY_CONTENTS:
4840 		if (s != NULL && *(s + 1) != '\0')
4841 			return (dump_path_impl(os, child_obj, s + 1, retobj));
4842 		zfs_fallthrough;
4843 	case DMU_OT_PLAIN_FILE_CONTENTS:
4844 		if (retobj != NULL) {
4845 			*retobj = child_obj;
4846 		} else {
4847 			dump_object(os, child_obj, dump_opt['v'], &header,
4848 			    NULL, 0);
4849 		}
4850 		return (0);
4851 	default:
4852 		(void) fprintf(stderr, "object %llu has non-file/directory "
4853 		    "type %d\n", (u_longlong_t)obj, doi.doi_type);
4854 		break;
4855 	}
4856 
4857 	return (EINVAL);
4858 }
4859 
4860 /*
4861  * Dump the blocks for the object specified by path inside the dataset.
4862  */
4863 static int
4864 dump_path(char *ds, char *path, uint64_t *retobj)
4865 {
4866 	int err;
4867 	objset_t *os;
4868 	uint64_t root_obj;
4869 
4870 	err = open_objset(ds, FTAG, &os);
4871 	if (err != 0)
4872 		return (err);
4873 
4874 	err = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1, &root_obj);
4875 	if (err != 0) {
4876 		(void) fprintf(stderr, "can't lookup root znode: %s\n",
4877 		    strerror(err));
4878 		close_objset(os, FTAG);
4879 		return (EINVAL);
4880 	}
4881 
4882 	(void) snprintf(curpath, sizeof (curpath), "dataset=%s path=/", ds);
4883 
4884 	err = dump_path_impl(os, root_obj, path, retobj);
4885 
4886 	close_objset(os, FTAG);
4887 	return (err);
4888 }
4889 
4890 static int
4891 dump_backup_bytes(objset_t *os, void *buf, int len, void *arg)
4892 {
4893 	const char *p = (const char *)buf;
4894 	ssize_t nwritten;
4895 
4896 	(void) os;
4897 	(void) arg;
4898 
4899 	/* Write the data out, handling short writes and signals. */
4900 	while ((nwritten = write(STDOUT_FILENO, p, len)) < len) {
4901 		if (nwritten < 0) {
4902 			if (errno == EINTR)
4903 				continue;
4904 			return (errno);
4905 		}
4906 		p += nwritten;
4907 		len -= nwritten;
4908 	}
4909 
4910 	return (0);
4911 }
4912 
4913 static void
4914 dump_backup(const char *pool, uint64_t objset_id, const char *flagstr)
4915 {
4916 	boolean_t embed = B_FALSE;
4917 	boolean_t large_block = B_FALSE;
4918 	boolean_t compress = B_FALSE;
4919 	boolean_t raw = B_FALSE;
4920 
4921 	const char *c;
4922 	for (c = flagstr; c != NULL && *c != '\0'; c++) {
4923 		switch (*c) {
4924 			case 'e':
4925 				embed = B_TRUE;
4926 				break;
4927 			case 'L':
4928 				large_block = B_TRUE;
4929 				break;
4930 			case 'c':
4931 				compress = B_TRUE;
4932 				break;
4933 			case 'w':
4934 				raw = B_TRUE;
4935 				break;
4936 			default:
4937 				fprintf(stderr, "dump_backup: invalid flag "
4938 				    "'%c'\n", *c);
4939 				return;
4940 		}
4941 	}
4942 
4943 	if (isatty(STDOUT_FILENO)) {
4944 		fprintf(stderr, "dump_backup: stream cannot be written "
4945 		    "to a terminal\n");
4946 		return;
4947 	}
4948 
4949 	offset_t off = 0;
4950 	dmu_send_outparams_t out = {
4951 	    .dso_outfunc = dump_backup_bytes,
4952 	    .dso_dryrun  = B_FALSE,
4953 	};
4954 
4955 	int err = dmu_send_obj(pool, objset_id, /* fromsnap */0, embed,
4956 	    large_block, compress, raw, /* saved */ B_FALSE, STDOUT_FILENO,
4957 	    &off, &out);
4958 	if (err != 0) {
4959 		fprintf(stderr, "dump_backup: dmu_send_obj: %s\n",
4960 		    strerror(err));
4961 		return;
4962 	}
4963 }
4964 
4965 static int
4966 zdb_copy_object(objset_t *os, uint64_t srcobj, char *destfile)
4967 {
4968 	int err = 0;
4969 	uint64_t size, readsize, oursize, offset;
4970 	ssize_t writesize;
4971 	sa_handle_t *hdl;
4972 
4973 	(void) printf("Copying object %" PRIu64 " to file %s\n", srcobj,
4974 	    destfile);
4975 
4976 	VERIFY3P(os, ==, sa_os);
4977 	if ((err = sa_handle_get(os, srcobj, NULL, SA_HDL_PRIVATE, &hdl))) {
4978 		(void) printf("Failed to get handle for SA znode\n");
4979 		return (err);
4980 	}
4981 	if ((err = sa_lookup(hdl, sa_attr_table[ZPL_SIZE], &size, 8))) {
4982 		(void) sa_handle_destroy(hdl);
4983 		return (err);
4984 	}
4985 	(void) sa_handle_destroy(hdl);
4986 
4987 	(void) printf("Object %" PRIu64 " is %" PRIu64 " bytes\n", srcobj,
4988 	    size);
4989 	if (size == 0) {
4990 		return (EINVAL);
4991 	}
4992 
4993 	int fd = open(destfile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
4994 	if (fd == -1)
4995 		return (errno);
4996 	/*
4997 	 * We cap the size at 1 mebibyte here to prevent
4998 	 * allocation failures and nigh-infinite printing if the
4999 	 * object is extremely large.
5000 	 */
5001 	oursize = MIN(size, 1 << 20);
5002 	offset = 0;
5003 	char *buf = kmem_alloc(oursize, KM_NOSLEEP);
5004 	if (buf == NULL) {
5005 		(void) close(fd);
5006 		return (ENOMEM);
5007 	}
5008 
5009 	while (offset < size) {
5010 		readsize = MIN(size - offset, 1 << 20);
5011 		err = dmu_read(os, srcobj, offset, readsize, buf, 0);
5012 		if (err != 0) {
5013 			(void) printf("got error %u from dmu_read\n", err);
5014 			kmem_free(buf, oursize);
5015 			(void) close(fd);
5016 			return (err);
5017 		}
5018 		if (dump_opt['v'] > 3) {
5019 			(void) printf("Read offset=%" PRIu64 " size=%" PRIu64
5020 			    " error=%d\n", offset, readsize, err);
5021 		}
5022 
5023 		writesize = write(fd, buf, readsize);
5024 		if (writesize < 0) {
5025 			err = errno;
5026 			break;
5027 		} else if (writesize != readsize) {
5028 			/* Incomplete write */
5029 			(void) fprintf(stderr, "Short write, only wrote %llu of"
5030 			    " %" PRIu64 " bytes, exiting...\n",
5031 			    (u_longlong_t)writesize, readsize);
5032 			break;
5033 		}
5034 
5035 		offset += readsize;
5036 	}
5037 
5038 	(void) close(fd);
5039 
5040 	if (buf != NULL)
5041 		kmem_free(buf, oursize);
5042 
5043 	return (err);
5044 }
5045 
5046 static boolean_t
5047 label_cksum_valid(vdev_label_t *label, uint64_t offset)
5048 {
5049 	zio_checksum_info_t *ci = &zio_checksum_table[ZIO_CHECKSUM_LABEL];
5050 	zio_cksum_t expected_cksum;
5051 	zio_cksum_t actual_cksum;
5052 	zio_cksum_t verifier;
5053 	zio_eck_t *eck;
5054 	int byteswap;
5055 
5056 	void *data = (char *)label + offsetof(vdev_label_t, vl_vdev_phys);
5057 	eck = (zio_eck_t *)((char *)(data) + VDEV_PHYS_SIZE) - 1;
5058 
5059 	offset += offsetof(vdev_label_t, vl_vdev_phys);
5060 	ZIO_SET_CHECKSUM(&verifier, offset, 0, 0, 0);
5061 
5062 	byteswap = (eck->zec_magic == BSWAP_64(ZEC_MAGIC));
5063 	if (byteswap)
5064 		byteswap_uint64_array(&verifier, sizeof (zio_cksum_t));
5065 
5066 	expected_cksum = eck->zec_cksum;
5067 	eck->zec_cksum = verifier;
5068 
5069 	abd_t *abd = abd_get_from_buf(data, VDEV_PHYS_SIZE);
5070 	ci->ci_func[byteswap](abd, VDEV_PHYS_SIZE, NULL, &actual_cksum);
5071 	abd_free(abd);
5072 
5073 	if (byteswap)
5074 		byteswap_uint64_array(&expected_cksum, sizeof (zio_cksum_t));
5075 
5076 	if (ZIO_CHECKSUM_EQUAL(actual_cksum, expected_cksum))
5077 		return (B_TRUE);
5078 
5079 	return (B_FALSE);
5080 }
5081 
5082 static int
5083 dump_label(const char *dev)
5084 {
5085 	char path[MAXPATHLEN];
5086 	zdb_label_t labels[VDEV_LABELS] = {{{{0}}}};
5087 	uint64_t psize, ashift, l2cache;
5088 	struct stat64 statbuf;
5089 	boolean_t config_found = B_FALSE;
5090 	boolean_t error = B_FALSE;
5091 	boolean_t read_l2arc_header = B_FALSE;
5092 	avl_tree_t config_tree;
5093 	avl_tree_t uberblock_tree;
5094 	void *node, *cookie;
5095 	int fd;
5096 
5097 	/*
5098 	 * Check if we were given absolute path and use it as is.
5099 	 * Otherwise if the provided vdev name doesn't point to a file,
5100 	 * try prepending expected disk paths and partition numbers.
5101 	 */
5102 	(void) strlcpy(path, dev, sizeof (path));
5103 	if (dev[0] != '/' && stat64(path, &statbuf) != 0) {
5104 		int error;
5105 
5106 		error = zfs_resolve_shortname(dev, path, MAXPATHLEN);
5107 		if (error == 0 && zfs_dev_is_whole_disk(path)) {
5108 			if (zfs_append_partition(path, MAXPATHLEN) == -1)
5109 				error = ENOENT;
5110 		}
5111 
5112 		if (error || (stat64(path, &statbuf) != 0)) {
5113 			(void) printf("failed to find device %s, try "
5114 			    "specifying absolute path instead\n", dev);
5115 			return (1);
5116 		}
5117 	}
5118 
5119 	if ((fd = open64(path, O_RDONLY)) < 0) {
5120 		(void) printf("cannot open '%s': %s\n", path, strerror(errno));
5121 		exit(1);
5122 	}
5123 
5124 	if (fstat64_blk(fd, &statbuf) != 0) {
5125 		(void) printf("failed to stat '%s': %s\n", path,
5126 		    strerror(errno));
5127 		(void) close(fd);
5128 		exit(1);
5129 	}
5130 
5131 	if (S_ISBLK(statbuf.st_mode) && zfs_dev_flush(fd) != 0)
5132 		(void) printf("failed to invalidate cache '%s' : %s\n", path,
5133 		    strerror(errno));
5134 
5135 	avl_create(&config_tree, cksum_record_compare,
5136 	    sizeof (cksum_record_t), offsetof(cksum_record_t, link));
5137 	avl_create(&uberblock_tree, cksum_record_compare,
5138 	    sizeof (cksum_record_t), offsetof(cksum_record_t, link));
5139 
5140 	psize = statbuf.st_size;
5141 	psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
5142 	ashift = SPA_MINBLOCKSHIFT;
5143 
5144 	/*
5145 	 * 1. Read the label from disk
5146 	 * 2. Verify label cksum
5147 	 * 3. Unpack the configuration and insert in config tree.
5148 	 * 4. Traverse all uberblocks and insert in uberblock tree.
5149 	 */
5150 	for (int l = 0; l < VDEV_LABELS; l++) {
5151 		zdb_label_t *label = &labels[l];
5152 		char *buf = label->label.vl_vdev_phys.vp_nvlist;
5153 		size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
5154 		nvlist_t *config;
5155 		cksum_record_t *rec;
5156 		zio_cksum_t cksum;
5157 		vdev_t vd;
5158 
5159 		label->label_offset = vdev_label_offset(psize, l, 0);
5160 
5161 		if (pread64(fd, &label->label, sizeof (label->label),
5162 		    label->label_offset) != sizeof (label->label)) {
5163 			if (!dump_opt['q'])
5164 				(void) printf("failed to read label %d\n", l);
5165 			label->read_failed = B_TRUE;
5166 			error = B_TRUE;
5167 			continue;
5168 		}
5169 
5170 		label->read_failed = B_FALSE;
5171 		label->cksum_valid = label_cksum_valid(&label->label,
5172 		    label->label_offset);
5173 
5174 		if (nvlist_unpack(buf, buflen, &config, 0) == 0) {
5175 			nvlist_t *vdev_tree = NULL;
5176 			size_t size;
5177 
5178 			if ((nvlist_lookup_nvlist(config,
5179 			    ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
5180 			    (nvlist_lookup_uint64(vdev_tree,
5181 			    ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
5182 				ashift = SPA_MINBLOCKSHIFT;
5183 
5184 			if (nvlist_size(config, &size, NV_ENCODE_XDR) != 0)
5185 				size = buflen;
5186 
5187 			/* If the device is a cache device read the header. */
5188 			if (!read_l2arc_header) {
5189 				if (nvlist_lookup_uint64(config,
5190 				    ZPOOL_CONFIG_POOL_STATE, &l2cache) == 0 &&
5191 				    l2cache == POOL_STATE_L2CACHE) {
5192 					read_l2arc_header = B_TRUE;
5193 				}
5194 			}
5195 
5196 			fletcher_4_native_varsize(buf, size, &cksum);
5197 			rec = cksum_record_insert(&config_tree, &cksum, l);
5198 
5199 			label->config = rec;
5200 			label->config_nv = config;
5201 			config_found = B_TRUE;
5202 		} else {
5203 			error = B_TRUE;
5204 		}
5205 
5206 		vd.vdev_ashift = ashift;
5207 		vd.vdev_top = &vd;
5208 
5209 		for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
5210 			uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
5211 			uberblock_t *ub = (void *)((char *)label + uoff);
5212 
5213 			if (uberblock_verify(ub))
5214 				continue;
5215 
5216 			fletcher_4_native_varsize(ub, sizeof (*ub), &cksum);
5217 			rec = cksum_record_insert(&uberblock_tree, &cksum, l);
5218 
5219 			label->uberblocks[i] = rec;
5220 		}
5221 	}
5222 
5223 	/*
5224 	 * Dump the label and uberblocks.
5225 	 */
5226 	for (int l = 0; l < VDEV_LABELS; l++) {
5227 		zdb_label_t *label = &labels[l];
5228 		size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
5229 
5230 		if (label->read_failed == B_TRUE)
5231 			continue;
5232 
5233 		if (label->config_nv) {
5234 			dump_config_from_label(label, buflen, l);
5235 		} else {
5236 			if (!dump_opt['q'])
5237 				(void) printf("failed to unpack label %d\n", l);
5238 		}
5239 
5240 		if (dump_opt['u'])
5241 			dump_label_uberblocks(label, ashift, l);
5242 
5243 		nvlist_free(label->config_nv);
5244 	}
5245 
5246 	/*
5247 	 * Dump the L2ARC header, if existent.
5248 	 */
5249 	if (read_l2arc_header)
5250 		error |= dump_l2arc_header(fd);
5251 
5252 	cookie = NULL;
5253 	while ((node = avl_destroy_nodes(&config_tree, &cookie)) != NULL)
5254 		umem_free(node, sizeof (cksum_record_t));
5255 
5256 	cookie = NULL;
5257 	while ((node = avl_destroy_nodes(&uberblock_tree, &cookie)) != NULL)
5258 		umem_free(node, sizeof (cksum_record_t));
5259 
5260 	avl_destroy(&config_tree);
5261 	avl_destroy(&uberblock_tree);
5262 
5263 	(void) close(fd);
5264 
5265 	return (config_found == B_FALSE ? 2 :
5266 	    (error == B_TRUE ? 1 : 0));
5267 }
5268 
5269 static uint64_t dataset_feature_count[SPA_FEATURES];
5270 static uint64_t global_feature_count[SPA_FEATURES];
5271 static uint64_t remap_deadlist_count = 0;
5272 
5273 static int
5274 dump_one_objset(const char *dsname, void *arg)
5275 {
5276 	(void) arg;
5277 	int error;
5278 	objset_t *os;
5279 	spa_feature_t f;
5280 
5281 	error = open_objset(dsname, FTAG, &os);
5282 	if (error != 0)
5283 		return (0);
5284 
5285 	for (f = 0; f < SPA_FEATURES; f++) {
5286 		if (!dsl_dataset_feature_is_active(dmu_objset_ds(os), f))
5287 			continue;
5288 		ASSERT(spa_feature_table[f].fi_flags &
5289 		    ZFEATURE_FLAG_PER_DATASET);
5290 		dataset_feature_count[f]++;
5291 	}
5292 
5293 	if (dsl_dataset_remap_deadlist_exists(dmu_objset_ds(os))) {
5294 		remap_deadlist_count++;
5295 	}
5296 
5297 	for (dsl_bookmark_node_t *dbn =
5298 	    avl_first(&dmu_objset_ds(os)->ds_bookmarks); dbn != NULL;
5299 	    dbn = AVL_NEXT(&dmu_objset_ds(os)->ds_bookmarks, dbn)) {
5300 		mos_obj_refd(dbn->dbn_phys.zbm_redaction_obj);
5301 		if (dbn->dbn_phys.zbm_redaction_obj != 0) {
5302 			global_feature_count[
5303 			    SPA_FEATURE_REDACTION_BOOKMARKS]++;
5304 			objset_t *mos = os->os_spa->spa_meta_objset;
5305 			dnode_t *rl;
5306 			VERIFY0(dnode_hold(mos,
5307 			    dbn->dbn_phys.zbm_redaction_obj, FTAG, &rl));
5308 			if (rl->dn_have_spill) {
5309 				global_feature_count[
5310 				    SPA_FEATURE_REDACTION_LIST_SPILL]++;
5311 			}
5312 		}
5313 		if (dbn->dbn_phys.zbm_flags & ZBM_FLAG_HAS_FBN)
5314 			global_feature_count[SPA_FEATURE_BOOKMARK_WRITTEN]++;
5315 	}
5316 
5317 	if (dsl_deadlist_is_open(&dmu_objset_ds(os)->ds_dir->dd_livelist) &&
5318 	    !dmu_objset_is_snapshot(os)) {
5319 		global_feature_count[SPA_FEATURE_LIVELIST]++;
5320 	}
5321 
5322 	dump_objset(os);
5323 	close_objset(os, FTAG);
5324 	fuid_table_destroy();
5325 	return (0);
5326 }
5327 
5328 /*
5329  * Block statistics.
5330  */
5331 #define	PSIZE_HISTO_SIZE (SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 2)
5332 typedef struct zdb_blkstats {
5333 	uint64_t zb_asize;
5334 	uint64_t zb_lsize;
5335 	uint64_t zb_psize;
5336 	uint64_t zb_count;
5337 	uint64_t zb_gangs;
5338 	uint64_t zb_ditto_samevdev;
5339 	uint64_t zb_ditto_same_ms;
5340 	uint64_t zb_psize_histogram[PSIZE_HISTO_SIZE];
5341 } zdb_blkstats_t;
5342 
5343 /*
5344  * Extended object types to report deferred frees and dedup auto-ditto blocks.
5345  */
5346 #define	ZDB_OT_DEFERRED	(DMU_OT_NUMTYPES + 0)
5347 #define	ZDB_OT_DITTO	(DMU_OT_NUMTYPES + 1)
5348 #define	ZDB_OT_OTHER	(DMU_OT_NUMTYPES + 2)
5349 #define	ZDB_OT_TOTAL	(DMU_OT_NUMTYPES + 3)
5350 
5351 static const char *zdb_ot_extname[] = {
5352 	"deferred free",
5353 	"dedup ditto",
5354 	"other",
5355 	"Total",
5356 };
5357 
5358 #define	ZB_TOTAL	DN_MAX_LEVELS
5359 #define	SPA_MAX_FOR_16M	(SPA_MAXBLOCKSHIFT+1)
5360 
5361 typedef struct zdb_brt_entry {
5362 	dva_t		zbre_dva;
5363 	uint64_t	zbre_refcount;
5364 	avl_node_t	zbre_node;
5365 } zdb_brt_entry_t;
5366 
5367 typedef struct zdb_cb {
5368 	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
5369 	uint64_t	zcb_removing_size;
5370 	uint64_t	zcb_checkpoint_size;
5371 	uint64_t	zcb_dedup_asize;
5372 	uint64_t	zcb_dedup_blocks;
5373 	uint64_t	zcb_clone_asize;
5374 	uint64_t	zcb_clone_blocks;
5375 	uint64_t	zcb_psize_count[SPA_MAX_FOR_16M];
5376 	uint64_t	zcb_lsize_count[SPA_MAX_FOR_16M];
5377 	uint64_t	zcb_asize_count[SPA_MAX_FOR_16M];
5378 	uint64_t	zcb_psize_len[SPA_MAX_FOR_16M];
5379 	uint64_t	zcb_lsize_len[SPA_MAX_FOR_16M];
5380 	uint64_t	zcb_asize_len[SPA_MAX_FOR_16M];
5381 	uint64_t	zcb_psize_total;
5382 	uint64_t	zcb_lsize_total;
5383 	uint64_t	zcb_asize_total;
5384 	uint64_t	zcb_embedded_blocks[NUM_BP_EMBEDDED_TYPES];
5385 	uint64_t	zcb_embedded_histogram[NUM_BP_EMBEDDED_TYPES]
5386 	    [BPE_PAYLOAD_SIZE + 1];
5387 	uint64_t	zcb_start;
5388 	hrtime_t	zcb_lastprint;
5389 	uint64_t	zcb_totalasize;
5390 	uint64_t	zcb_errors[256];
5391 	int		zcb_readfails;
5392 	int		zcb_haderrors;
5393 	spa_t		*zcb_spa;
5394 	uint32_t	**zcb_vd_obsolete_counts;
5395 	avl_tree_t	zcb_brt;
5396 	boolean_t	zcb_brt_is_active;
5397 } zdb_cb_t;
5398 
5399 /* test if two DVA offsets from same vdev are within the same metaslab */
5400 static boolean_t
5401 same_metaslab(spa_t *spa, uint64_t vdev, uint64_t off1, uint64_t off2)
5402 {
5403 	vdev_t *vd = vdev_lookup_top(spa, vdev);
5404 	uint64_t ms_shift = vd->vdev_ms_shift;
5405 
5406 	return ((off1 >> ms_shift) == (off2 >> ms_shift));
5407 }
5408 
5409 /*
5410  * Used to simplify reporting of the histogram data.
5411  */
5412 typedef struct one_histo {
5413 	const char *name;
5414 	uint64_t *count;
5415 	uint64_t *len;
5416 	uint64_t cumulative;
5417 } one_histo_t;
5418 
5419 /*
5420  * The number of separate histograms processed for psize, lsize and asize.
5421  */
5422 #define	NUM_HISTO 3
5423 
5424 /*
5425  * This routine will create a fixed column size output of three different
5426  * histograms showing by blocksize of 512 - 2^ SPA_MAX_FOR_16M
5427  * the count, length and cumulative length of the psize, lsize and
5428  * asize blocks.
5429  *
5430  * All three types of blocks are listed on a single line
5431  *
5432  * By default the table is printed in nicenumber format (e.g. 123K) but
5433  * if the '-P' parameter is specified then the full raw number (parseable)
5434  * is printed out.
5435  */
5436 static void
5437 dump_size_histograms(zdb_cb_t *zcb)
5438 {
5439 	/*
5440 	 * A temporary buffer that allows us to convert a number into
5441 	 * a string using zdb_nicenumber to allow either raw or human
5442 	 * readable numbers to be output.
5443 	 */
5444 	char numbuf[32];
5445 
5446 	/*
5447 	 * Define titles which are used in the headers of the tables
5448 	 * printed by this routine.
5449 	 */
5450 	const char blocksize_title1[] = "block";
5451 	const char blocksize_title2[] = "size";
5452 	const char count_title[] = "Count";
5453 	const char length_title[] = "Size";
5454 	const char cumulative_title[] = "Cum.";
5455 
5456 	/*
5457 	 * Setup the histogram arrays (psize, lsize, and asize).
5458 	 */
5459 	one_histo_t parm_histo[NUM_HISTO];
5460 
5461 	parm_histo[0].name = "psize";
5462 	parm_histo[0].count = zcb->zcb_psize_count;
5463 	parm_histo[0].len = zcb->zcb_psize_len;
5464 	parm_histo[0].cumulative = 0;
5465 
5466 	parm_histo[1].name = "lsize";
5467 	parm_histo[1].count = zcb->zcb_lsize_count;
5468 	parm_histo[1].len = zcb->zcb_lsize_len;
5469 	parm_histo[1].cumulative = 0;
5470 
5471 	parm_histo[2].name = "asize";
5472 	parm_histo[2].count = zcb->zcb_asize_count;
5473 	parm_histo[2].len = zcb->zcb_asize_len;
5474 	parm_histo[2].cumulative = 0;
5475 
5476 
5477 	(void) printf("\nBlock Size Histogram\n");
5478 	/*
5479 	 * Print the first line titles
5480 	 */
5481 	if (dump_opt['P'])
5482 		(void) printf("\n%s\t", blocksize_title1);
5483 	else
5484 		(void) printf("\n%7s   ", blocksize_title1);
5485 
5486 	for (int j = 0; j < NUM_HISTO; j++) {
5487 		if (dump_opt['P']) {
5488 			if (j < NUM_HISTO - 1) {
5489 				(void) printf("%s\t\t\t", parm_histo[j].name);
5490 			} else {
5491 				/* Don't print trailing spaces */
5492 				(void) printf("  %s", parm_histo[j].name);
5493 			}
5494 		} else {
5495 			if (j < NUM_HISTO - 1) {
5496 				/* Left aligned strings in the output */
5497 				(void) printf("%-7s              ",
5498 				    parm_histo[j].name);
5499 			} else {
5500 				/* Don't print trailing spaces */
5501 				(void) printf("%s", parm_histo[j].name);
5502 			}
5503 		}
5504 	}
5505 	(void) printf("\n");
5506 
5507 	/*
5508 	 * Print the second line titles
5509 	 */
5510 	if (dump_opt['P']) {
5511 		(void) printf("%s\t", blocksize_title2);
5512 	} else {
5513 		(void) printf("%7s ", blocksize_title2);
5514 	}
5515 
5516 	for (int i = 0; i < NUM_HISTO; i++) {
5517 		if (dump_opt['P']) {
5518 			(void) printf("%s\t%s\t%s\t",
5519 			    count_title, length_title, cumulative_title);
5520 		} else {
5521 			(void) printf("%7s%7s%7s",
5522 			    count_title, length_title, cumulative_title);
5523 		}
5524 	}
5525 	(void) printf("\n");
5526 
5527 	/*
5528 	 * Print the rows
5529 	 */
5530 	for (int i = SPA_MINBLOCKSHIFT; i < SPA_MAX_FOR_16M; i++) {
5531 
5532 		/*
5533 		 * Print the first column showing the blocksize
5534 		 */
5535 		zdb_nicenum((1ULL << i), numbuf, sizeof (numbuf));
5536 
5537 		if (dump_opt['P']) {
5538 			printf("%s", numbuf);
5539 		} else {
5540 			printf("%7s:", numbuf);
5541 		}
5542 
5543 		/*
5544 		 * Print the remaining set of 3 columns per size:
5545 		 * for psize, lsize and asize
5546 		 */
5547 		for (int j = 0; j < NUM_HISTO; j++) {
5548 			parm_histo[j].cumulative += parm_histo[j].len[i];
5549 
5550 			zdb_nicenum(parm_histo[j].count[i],
5551 			    numbuf, sizeof (numbuf));
5552 			if (dump_opt['P'])
5553 				(void) printf("\t%s", numbuf);
5554 			else
5555 				(void) printf("%7s", numbuf);
5556 
5557 			zdb_nicenum(parm_histo[j].len[i],
5558 			    numbuf, sizeof (numbuf));
5559 			if (dump_opt['P'])
5560 				(void) printf("\t%s", numbuf);
5561 			else
5562 				(void) printf("%7s", numbuf);
5563 
5564 			zdb_nicenum(parm_histo[j].cumulative,
5565 			    numbuf, sizeof (numbuf));
5566 			if (dump_opt['P'])
5567 				(void) printf("\t%s", numbuf);
5568 			else
5569 				(void) printf("%7s", numbuf);
5570 		}
5571 		(void) printf("\n");
5572 	}
5573 }
5574 
5575 static void
5576 zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
5577     dmu_object_type_t type)
5578 {
5579 	uint64_t refcnt = 0;
5580 	int i;
5581 
5582 	ASSERT(type < ZDB_OT_TOTAL);
5583 
5584 	if (zilog && zil_bp_tree_add(zilog, bp) != 0)
5585 		return;
5586 
5587 	spa_config_enter(zcb->zcb_spa, SCL_CONFIG, FTAG, RW_READER);
5588 
5589 	for (i = 0; i < 4; i++) {
5590 		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
5591 		int t = (i & 1) ? type : ZDB_OT_TOTAL;
5592 		int equal;
5593 		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
5594 
5595 		zb->zb_asize += BP_GET_ASIZE(bp);
5596 		zb->zb_lsize += BP_GET_LSIZE(bp);
5597 		zb->zb_psize += BP_GET_PSIZE(bp);
5598 		zb->zb_count++;
5599 
5600 		/*
5601 		 * The histogram is only big enough to record blocks up to
5602 		 * SPA_OLD_MAXBLOCKSIZE; larger blocks go into the last,
5603 		 * "other", bucket.
5604 		 */
5605 		unsigned idx = BP_GET_PSIZE(bp) >> SPA_MINBLOCKSHIFT;
5606 		idx = MIN(idx, SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 1);
5607 		zb->zb_psize_histogram[idx]++;
5608 
5609 		zb->zb_gangs += BP_COUNT_GANG(bp);
5610 
5611 		switch (BP_GET_NDVAS(bp)) {
5612 		case 2:
5613 			if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5614 			    DVA_GET_VDEV(&bp->blk_dva[1])) {
5615 				zb->zb_ditto_samevdev++;
5616 
5617 				if (same_metaslab(zcb->zcb_spa,
5618 				    DVA_GET_VDEV(&bp->blk_dva[0]),
5619 				    DVA_GET_OFFSET(&bp->blk_dva[0]),
5620 				    DVA_GET_OFFSET(&bp->blk_dva[1])))
5621 					zb->zb_ditto_same_ms++;
5622 			}
5623 			break;
5624 		case 3:
5625 			equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5626 			    DVA_GET_VDEV(&bp->blk_dva[1])) +
5627 			    (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5628 			    DVA_GET_VDEV(&bp->blk_dva[2])) +
5629 			    (DVA_GET_VDEV(&bp->blk_dva[1]) ==
5630 			    DVA_GET_VDEV(&bp->blk_dva[2]));
5631 			if (equal != 0) {
5632 				zb->zb_ditto_samevdev++;
5633 
5634 				if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5635 				    DVA_GET_VDEV(&bp->blk_dva[1]) &&
5636 				    same_metaslab(zcb->zcb_spa,
5637 				    DVA_GET_VDEV(&bp->blk_dva[0]),
5638 				    DVA_GET_OFFSET(&bp->blk_dva[0]),
5639 				    DVA_GET_OFFSET(&bp->blk_dva[1])))
5640 					zb->zb_ditto_same_ms++;
5641 				else if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5642 				    DVA_GET_VDEV(&bp->blk_dva[2]) &&
5643 				    same_metaslab(zcb->zcb_spa,
5644 				    DVA_GET_VDEV(&bp->blk_dva[0]),
5645 				    DVA_GET_OFFSET(&bp->blk_dva[0]),
5646 				    DVA_GET_OFFSET(&bp->blk_dva[2])))
5647 					zb->zb_ditto_same_ms++;
5648 				else if (DVA_GET_VDEV(&bp->blk_dva[1]) ==
5649 				    DVA_GET_VDEV(&bp->blk_dva[2]) &&
5650 				    same_metaslab(zcb->zcb_spa,
5651 				    DVA_GET_VDEV(&bp->blk_dva[1]),
5652 				    DVA_GET_OFFSET(&bp->blk_dva[1]),
5653 				    DVA_GET_OFFSET(&bp->blk_dva[2])))
5654 					zb->zb_ditto_same_ms++;
5655 			}
5656 			break;
5657 		}
5658 	}
5659 
5660 	spa_config_exit(zcb->zcb_spa, SCL_CONFIG, FTAG);
5661 
5662 	if (BP_IS_EMBEDDED(bp)) {
5663 		zcb->zcb_embedded_blocks[BPE_GET_ETYPE(bp)]++;
5664 		zcb->zcb_embedded_histogram[BPE_GET_ETYPE(bp)]
5665 		    [BPE_GET_PSIZE(bp)]++;
5666 		return;
5667 	}
5668 	/*
5669 	 * The binning histogram bins by powers of two up to
5670 	 * SPA_MAXBLOCKSIZE rather than creating bins for
5671 	 * every possible blocksize found in the pool.
5672 	 */
5673 	int bin = highbit64(BP_GET_PSIZE(bp)) - 1;
5674 
5675 	zcb->zcb_psize_count[bin]++;
5676 	zcb->zcb_psize_len[bin] += BP_GET_PSIZE(bp);
5677 	zcb->zcb_psize_total += BP_GET_PSIZE(bp);
5678 
5679 	bin = highbit64(BP_GET_LSIZE(bp)) - 1;
5680 
5681 	zcb->zcb_lsize_count[bin]++;
5682 	zcb->zcb_lsize_len[bin] += BP_GET_LSIZE(bp);
5683 	zcb->zcb_lsize_total += BP_GET_LSIZE(bp);
5684 
5685 	bin = highbit64(BP_GET_ASIZE(bp)) - 1;
5686 
5687 	zcb->zcb_asize_count[bin]++;
5688 	zcb->zcb_asize_len[bin] += BP_GET_ASIZE(bp);
5689 	zcb->zcb_asize_total += BP_GET_ASIZE(bp);
5690 
5691 	if (zcb->zcb_brt_is_active && brt_maybe_exists(zcb->zcb_spa, bp)) {
5692 		/*
5693 		 * Cloned blocks are special. We need to count them, so we can
5694 		 * later uncount them when reporting leaked space, and we must
5695 		 * only claim them them once.
5696 		 *
5697 		 * To do this, we keep our own in-memory BRT. For each block
5698 		 * we haven't seen before, we look it up in the real BRT and
5699 		 * if its there, we note it and its refcount then proceed as
5700 		 * normal. If we see the block again, we count it as a clone
5701 		 * and then give it no further consideration.
5702 		 */
5703 		zdb_brt_entry_t zbre_search, *zbre;
5704 		avl_index_t where;
5705 
5706 		zbre_search.zbre_dva = bp->blk_dva[0];
5707 		zbre = avl_find(&zcb->zcb_brt, &zbre_search, &where);
5708 		if (zbre != NULL) {
5709 			zcb->zcb_clone_asize += BP_GET_ASIZE(bp);
5710 			zcb->zcb_clone_blocks++;
5711 
5712 			zbre->zbre_refcount--;
5713 			if (zbre->zbre_refcount == 0) {
5714 				avl_remove(&zcb->zcb_brt, zbre);
5715 				umem_free(zbre, sizeof (zdb_brt_entry_t));
5716 			}
5717 			return;
5718 		}
5719 
5720 		uint64_t crefcnt = brt_entry_get_refcount(zcb->zcb_spa, bp);
5721 		if (crefcnt > 0) {
5722 			zbre = umem_zalloc(sizeof (zdb_brt_entry_t),
5723 			    UMEM_NOFAIL);
5724 			zbre->zbre_dva = bp->blk_dva[0];
5725 			zbre->zbre_refcount = crefcnt;
5726 			avl_insert(&zcb->zcb_brt, zbre, where);
5727 		}
5728 	}
5729 
5730 	if (dump_opt['L'])
5731 		return;
5732 
5733 	if (BP_GET_DEDUP(bp)) {
5734 		ddt_t *ddt;
5735 		ddt_entry_t *dde;
5736 
5737 		ddt = ddt_select(zcb->zcb_spa, bp);
5738 		ddt_enter(ddt);
5739 		dde = ddt_lookup(ddt, bp, B_FALSE);
5740 
5741 		if (dde == NULL) {
5742 			refcnt = 0;
5743 		} else {
5744 			ddt_phys_t *ddp = ddt_phys_select(dde, bp);
5745 			ddt_phys_decref(ddp);
5746 			refcnt = ddp->ddp_refcnt;
5747 			if (ddt_phys_total_refcnt(dde) == 0)
5748 				ddt_remove(ddt, dde);
5749 		}
5750 		ddt_exit(ddt);
5751 	}
5752 
5753 	VERIFY3U(zio_wait(zio_claim(NULL, zcb->zcb_spa,
5754 	    refcnt ? 0 : spa_min_claim_txg(zcb->zcb_spa),
5755 	    bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
5756 }
5757 
5758 static void
5759 zdb_blkptr_done(zio_t *zio)
5760 {
5761 	spa_t *spa = zio->io_spa;
5762 	blkptr_t *bp = zio->io_bp;
5763 	int ioerr = zio->io_error;
5764 	zdb_cb_t *zcb = zio->io_private;
5765 	zbookmark_phys_t *zb = &zio->io_bookmark;
5766 
5767 	mutex_enter(&spa->spa_scrub_lock);
5768 	spa->spa_load_verify_bytes -= BP_GET_PSIZE(bp);
5769 	cv_broadcast(&spa->spa_scrub_io_cv);
5770 
5771 	if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
5772 		char blkbuf[BP_SPRINTF_LEN];
5773 
5774 		zcb->zcb_haderrors = 1;
5775 		zcb->zcb_errors[ioerr]++;
5776 
5777 		if (dump_opt['b'] >= 2)
5778 			snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
5779 		else
5780 			blkbuf[0] = '\0';
5781 
5782 		(void) printf("zdb_blkptr_cb: "
5783 		    "Got error %d reading "
5784 		    "<%llu, %llu, %lld, %llx> %s -- skipping\n",
5785 		    ioerr,
5786 		    (u_longlong_t)zb->zb_objset,
5787 		    (u_longlong_t)zb->zb_object,
5788 		    (u_longlong_t)zb->zb_level,
5789 		    (u_longlong_t)zb->zb_blkid,
5790 		    blkbuf);
5791 	}
5792 	mutex_exit(&spa->spa_scrub_lock);
5793 
5794 	abd_free(zio->io_abd);
5795 }
5796 
5797 static int
5798 zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
5799     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
5800 {
5801 	zdb_cb_t *zcb = arg;
5802 	dmu_object_type_t type;
5803 	boolean_t is_metadata;
5804 
5805 	if (zb->zb_level == ZB_DNODE_LEVEL)
5806 		return (0);
5807 
5808 	if (dump_opt['b'] >= 5 && bp->blk_birth > 0) {
5809 		char blkbuf[BP_SPRINTF_LEN];
5810 		snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
5811 		(void) printf("objset %llu object %llu "
5812 		    "level %lld offset 0x%llx %s\n",
5813 		    (u_longlong_t)zb->zb_objset,
5814 		    (u_longlong_t)zb->zb_object,
5815 		    (longlong_t)zb->zb_level,
5816 		    (u_longlong_t)blkid2offset(dnp, bp, zb),
5817 		    blkbuf);
5818 	}
5819 
5820 	if (BP_IS_HOLE(bp) || BP_IS_REDACTED(bp))
5821 		return (0);
5822 
5823 	type = BP_GET_TYPE(bp);
5824 
5825 	zdb_count_block(zcb, zilog, bp,
5826 	    (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
5827 
5828 	is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
5829 
5830 	if (!BP_IS_EMBEDDED(bp) &&
5831 	    (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata))) {
5832 		size_t size = BP_GET_PSIZE(bp);
5833 		abd_t *abd = abd_alloc(size, B_FALSE);
5834 		int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
5835 
5836 		/* If it's an intent log block, failure is expected. */
5837 		if (zb->zb_level == ZB_ZIL_LEVEL)
5838 			flags |= ZIO_FLAG_SPECULATIVE;
5839 
5840 		mutex_enter(&spa->spa_scrub_lock);
5841 		while (spa->spa_load_verify_bytes > max_inflight_bytes)
5842 			cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
5843 		spa->spa_load_verify_bytes += size;
5844 		mutex_exit(&spa->spa_scrub_lock);
5845 
5846 		zio_nowait(zio_read(NULL, spa, bp, abd, size,
5847 		    zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
5848 	}
5849 
5850 	zcb->zcb_readfails = 0;
5851 
5852 	/* only call gethrtime() every 100 blocks */
5853 	static int iters;
5854 	if (++iters > 100)
5855 		iters = 0;
5856 	else
5857 		return (0);
5858 
5859 	if (dump_opt['b'] < 5 && gethrtime() > zcb->zcb_lastprint + NANOSEC) {
5860 		uint64_t now = gethrtime();
5861 		char buf[10];
5862 		uint64_t bytes = zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL].zb_asize;
5863 		uint64_t kb_per_sec =
5864 		    1 + bytes / (1 + ((now - zcb->zcb_start) / 1000 / 1000));
5865 		uint64_t sec_remaining =
5866 		    (zcb->zcb_totalasize - bytes) / 1024 / kb_per_sec;
5867 
5868 		/* make sure nicenum has enough space */
5869 		_Static_assert(sizeof (buf) >= NN_NUMBUF_SZ, "buf truncated");
5870 
5871 		zfs_nicebytes(bytes, buf, sizeof (buf));
5872 		(void) fprintf(stderr,
5873 		    "\r%5s completed (%4"PRIu64"MB/s) "
5874 		    "estimated time remaining: "
5875 		    "%"PRIu64"hr %02"PRIu64"min %02"PRIu64"sec        ",
5876 		    buf, kb_per_sec / 1024,
5877 		    sec_remaining / 60 / 60,
5878 		    sec_remaining / 60 % 60,
5879 		    sec_remaining % 60);
5880 
5881 		zcb->zcb_lastprint = now;
5882 	}
5883 
5884 	return (0);
5885 }
5886 
5887 static void
5888 zdb_leak(void *arg, uint64_t start, uint64_t size)
5889 {
5890 	vdev_t *vd = arg;
5891 
5892 	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
5893 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
5894 }
5895 
5896 static metaslab_ops_t zdb_metaslab_ops = {
5897 	NULL	/* alloc */
5898 };
5899 
5900 static int
5901 load_unflushed_svr_segs_cb(spa_t *spa, space_map_entry_t *sme,
5902     uint64_t txg, void *arg)
5903 {
5904 	spa_vdev_removal_t *svr = arg;
5905 
5906 	uint64_t offset = sme->sme_offset;
5907 	uint64_t size = sme->sme_run;
5908 
5909 	/* skip vdevs we don't care about */
5910 	if (sme->sme_vdev != svr->svr_vdev_id)
5911 		return (0);
5912 
5913 	vdev_t *vd = vdev_lookup_top(spa, sme->sme_vdev);
5914 	metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5915 	ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
5916 
5917 	if (txg < metaslab_unflushed_txg(ms))
5918 		return (0);
5919 
5920 	if (sme->sme_type == SM_ALLOC)
5921 		range_tree_add(svr->svr_allocd_segs, offset, size);
5922 	else
5923 		range_tree_remove(svr->svr_allocd_segs, offset, size);
5924 
5925 	return (0);
5926 }
5927 
5928 static void
5929 claim_segment_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5930     uint64_t size, void *arg)
5931 {
5932 	(void) inner_offset, (void) arg;
5933 
5934 	/*
5935 	 * This callback was called through a remap from
5936 	 * a device being removed. Therefore, the vdev that
5937 	 * this callback is applied to is a concrete
5938 	 * vdev.
5939 	 */
5940 	ASSERT(vdev_is_concrete(vd));
5941 
5942 	VERIFY0(metaslab_claim_impl(vd, offset, size,
5943 	    spa_min_claim_txg(vd->vdev_spa)));
5944 }
5945 
5946 static void
5947 claim_segment_cb(void *arg, uint64_t offset, uint64_t size)
5948 {
5949 	vdev_t *vd = arg;
5950 
5951 	vdev_indirect_ops.vdev_op_remap(vd, offset, size,
5952 	    claim_segment_impl_cb, NULL);
5953 }
5954 
5955 /*
5956  * After accounting for all allocated blocks that are directly referenced,
5957  * we might have missed a reference to a block from a partially complete
5958  * (and thus unused) indirect mapping object. We perform a secondary pass
5959  * through the metaslabs we have already mapped and claim the destination
5960  * blocks.
5961  */
5962 static void
5963 zdb_claim_removing(spa_t *spa, zdb_cb_t *zcb)
5964 {
5965 	if (dump_opt['L'])
5966 		return;
5967 
5968 	if (spa->spa_vdev_removal == NULL)
5969 		return;
5970 
5971 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5972 
5973 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
5974 	vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
5975 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
5976 
5977 	ASSERT0(range_tree_space(svr->svr_allocd_segs));
5978 
5979 	range_tree_t *allocs = range_tree_create(NULL, RANGE_SEG64, NULL, 0, 0);
5980 	for (uint64_t msi = 0; msi < vd->vdev_ms_count; msi++) {
5981 		metaslab_t *msp = vd->vdev_ms[msi];
5982 
5983 		ASSERT0(range_tree_space(allocs));
5984 		if (msp->ms_sm != NULL)
5985 			VERIFY0(space_map_load(msp->ms_sm, allocs, SM_ALLOC));
5986 		range_tree_vacate(allocs, range_tree_add, svr->svr_allocd_segs);
5987 	}
5988 	range_tree_destroy(allocs);
5989 
5990 	iterate_through_spacemap_logs(spa, load_unflushed_svr_segs_cb, svr);
5991 
5992 	/*
5993 	 * Clear everything past what has been synced,
5994 	 * because we have not allocated mappings for
5995 	 * it yet.
5996 	 */
5997 	range_tree_clear(svr->svr_allocd_segs,
5998 	    vdev_indirect_mapping_max_offset(vim),
5999 	    vd->vdev_asize - vdev_indirect_mapping_max_offset(vim));
6000 
6001 	zcb->zcb_removing_size += range_tree_space(svr->svr_allocd_segs);
6002 	range_tree_vacate(svr->svr_allocd_segs, claim_segment_cb, vd);
6003 
6004 	spa_config_exit(spa, SCL_CONFIG, FTAG);
6005 }
6006 
6007 static int
6008 increment_indirect_mapping_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
6009     dmu_tx_t *tx)
6010 {
6011 	(void) tx;
6012 	zdb_cb_t *zcb = arg;
6013 	spa_t *spa = zcb->zcb_spa;
6014 	vdev_t *vd;
6015 	const dva_t *dva = &bp->blk_dva[0];
6016 
6017 	ASSERT(!bp_freed);
6018 	ASSERT(!dump_opt['L']);
6019 	ASSERT3U(BP_GET_NDVAS(bp), ==, 1);
6020 
6021 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
6022 	vd = vdev_lookup_top(zcb->zcb_spa, DVA_GET_VDEV(dva));
6023 	ASSERT3P(vd, !=, NULL);
6024 	spa_config_exit(spa, SCL_VDEV, FTAG);
6025 
6026 	ASSERT(vd->vdev_indirect_config.vic_mapping_object != 0);
6027 	ASSERT3P(zcb->zcb_vd_obsolete_counts[vd->vdev_id], !=, NULL);
6028 
6029 	vdev_indirect_mapping_increment_obsolete_count(
6030 	    vd->vdev_indirect_mapping,
6031 	    DVA_GET_OFFSET(dva), DVA_GET_ASIZE(dva),
6032 	    zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
6033 
6034 	return (0);
6035 }
6036 
6037 static uint32_t *
6038 zdb_load_obsolete_counts(vdev_t *vd)
6039 {
6040 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6041 	spa_t *spa = vd->vdev_spa;
6042 	spa_condensing_indirect_phys_t *scip =
6043 	    &spa->spa_condensing_indirect_phys;
6044 	uint64_t obsolete_sm_object;
6045 	uint32_t *counts;
6046 
6047 	VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
6048 	EQUIV(obsolete_sm_object != 0, vd->vdev_obsolete_sm != NULL);
6049 	counts = vdev_indirect_mapping_load_obsolete_counts(vim);
6050 	if (vd->vdev_obsolete_sm != NULL) {
6051 		vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
6052 		    vd->vdev_obsolete_sm);
6053 	}
6054 	if (scip->scip_vdev == vd->vdev_id &&
6055 	    scip->scip_prev_obsolete_sm_object != 0) {
6056 		space_map_t *prev_obsolete_sm = NULL;
6057 		VERIFY0(space_map_open(&prev_obsolete_sm, spa->spa_meta_objset,
6058 		    scip->scip_prev_obsolete_sm_object, 0, vd->vdev_asize, 0));
6059 		vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
6060 		    prev_obsolete_sm);
6061 		space_map_close(prev_obsolete_sm);
6062 	}
6063 	return (counts);
6064 }
6065 
6066 static void
6067 zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
6068 {
6069 	ddt_bookmark_t ddb = {0};
6070 	ddt_entry_t dde;
6071 	int error;
6072 	int p;
6073 
6074 	ASSERT(!dump_opt['L']);
6075 
6076 	while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
6077 		blkptr_t blk;
6078 		ddt_phys_t *ddp = dde.dde_phys;
6079 
6080 		if (ddb.ddb_class == DDT_CLASS_UNIQUE)
6081 			return;
6082 
6083 		ASSERT(ddt_phys_total_refcnt(&dde) > 1);
6084 
6085 		for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
6086 			if (ddp->ddp_phys_birth == 0)
6087 				continue;
6088 			ddt_bp_create(ddb.ddb_checksum,
6089 			    &dde.dde_key, ddp, &blk);
6090 			if (p == DDT_PHYS_DITTO) {
6091 				zdb_count_block(zcb, NULL, &blk, ZDB_OT_DITTO);
6092 			} else {
6093 				zcb->zcb_dedup_asize +=
6094 				    BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
6095 				zcb->zcb_dedup_blocks++;
6096 			}
6097 		}
6098 		ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
6099 		ddt_enter(ddt);
6100 		VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
6101 		ddt_exit(ddt);
6102 	}
6103 
6104 	ASSERT(error == ENOENT);
6105 }
6106 
6107 typedef struct checkpoint_sm_exclude_entry_arg {
6108 	vdev_t *cseea_vd;
6109 	uint64_t cseea_checkpoint_size;
6110 } checkpoint_sm_exclude_entry_arg_t;
6111 
6112 static int
6113 checkpoint_sm_exclude_entry_cb(space_map_entry_t *sme, void *arg)
6114 {
6115 	checkpoint_sm_exclude_entry_arg_t *cseea = arg;
6116 	vdev_t *vd = cseea->cseea_vd;
6117 	metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
6118 	uint64_t end = sme->sme_offset + sme->sme_run;
6119 
6120 	ASSERT(sme->sme_type == SM_FREE);
6121 
6122 	/*
6123 	 * Since the vdev_checkpoint_sm exists in the vdev level
6124 	 * and the ms_sm space maps exist in the metaslab level,
6125 	 * an entry in the checkpoint space map could theoretically
6126 	 * cross the boundaries of the metaslab that it belongs.
6127 	 *
6128 	 * In reality, because of the way that we populate and
6129 	 * manipulate the checkpoint's space maps currently,
6130 	 * there shouldn't be any entries that cross metaslabs.
6131 	 * Hence the assertion below.
6132 	 *
6133 	 * That said, there is no fundamental requirement that
6134 	 * the checkpoint's space map entries should not cross
6135 	 * metaslab boundaries. So if needed we could add code
6136 	 * that handles metaslab-crossing segments in the future.
6137 	 */
6138 	VERIFY3U(sme->sme_offset, >=, ms->ms_start);
6139 	VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
6140 
6141 	/*
6142 	 * By removing the entry from the allocated segments we
6143 	 * also verify that the entry is there to begin with.
6144 	 */
6145 	mutex_enter(&ms->ms_lock);
6146 	range_tree_remove(ms->ms_allocatable, sme->sme_offset, sme->sme_run);
6147 	mutex_exit(&ms->ms_lock);
6148 
6149 	cseea->cseea_checkpoint_size += sme->sme_run;
6150 	return (0);
6151 }
6152 
6153 static void
6154 zdb_leak_init_vdev_exclude_checkpoint(vdev_t *vd, zdb_cb_t *zcb)
6155 {
6156 	spa_t *spa = vd->vdev_spa;
6157 	space_map_t *checkpoint_sm = NULL;
6158 	uint64_t checkpoint_sm_obj;
6159 
6160 	/*
6161 	 * If there is no vdev_top_zap, we are in a pool whose
6162 	 * version predates the pool checkpoint feature.
6163 	 */
6164 	if (vd->vdev_top_zap == 0)
6165 		return;
6166 
6167 	/*
6168 	 * If there is no reference of the vdev_checkpoint_sm in
6169 	 * the vdev_top_zap, then one of the following scenarios
6170 	 * is true:
6171 	 *
6172 	 * 1] There is no checkpoint
6173 	 * 2] There is a checkpoint, but no checkpointed blocks
6174 	 *    have been freed yet
6175 	 * 3] The current vdev is indirect
6176 	 *
6177 	 * In these cases we return immediately.
6178 	 */
6179 	if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
6180 	    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
6181 		return;
6182 
6183 	VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
6184 	    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1,
6185 	    &checkpoint_sm_obj));
6186 
6187 	checkpoint_sm_exclude_entry_arg_t cseea;
6188 	cseea.cseea_vd = vd;
6189 	cseea.cseea_checkpoint_size = 0;
6190 
6191 	VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
6192 	    checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
6193 
6194 	VERIFY0(space_map_iterate(checkpoint_sm,
6195 	    space_map_length(checkpoint_sm),
6196 	    checkpoint_sm_exclude_entry_cb, &cseea));
6197 	space_map_close(checkpoint_sm);
6198 
6199 	zcb->zcb_checkpoint_size += cseea.cseea_checkpoint_size;
6200 }
6201 
6202 static void
6203 zdb_leak_init_exclude_checkpoint(spa_t *spa, zdb_cb_t *zcb)
6204 {
6205 	ASSERT(!dump_opt['L']);
6206 
6207 	vdev_t *rvd = spa->spa_root_vdev;
6208 	for (uint64_t c = 0; c < rvd->vdev_children; c++) {
6209 		ASSERT3U(c, ==, rvd->vdev_child[c]->vdev_id);
6210 		zdb_leak_init_vdev_exclude_checkpoint(rvd->vdev_child[c], zcb);
6211 	}
6212 }
6213 
6214 static int
6215 count_unflushed_space_cb(spa_t *spa, space_map_entry_t *sme,
6216     uint64_t txg, void *arg)
6217 {
6218 	int64_t *ualloc_space = arg;
6219 
6220 	uint64_t offset = sme->sme_offset;
6221 	uint64_t vdev_id = sme->sme_vdev;
6222 
6223 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
6224 	if (!vdev_is_concrete(vd))
6225 		return (0);
6226 
6227 	metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
6228 	ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
6229 
6230 	if (txg < metaslab_unflushed_txg(ms))
6231 		return (0);
6232 
6233 	if (sme->sme_type == SM_ALLOC)
6234 		*ualloc_space += sme->sme_run;
6235 	else
6236 		*ualloc_space -= sme->sme_run;
6237 
6238 	return (0);
6239 }
6240 
6241 static int64_t
6242 get_unflushed_alloc_space(spa_t *spa)
6243 {
6244 	if (dump_opt['L'])
6245 		return (0);
6246 
6247 	int64_t ualloc_space = 0;
6248 	iterate_through_spacemap_logs(spa, count_unflushed_space_cb,
6249 	    &ualloc_space);
6250 	return (ualloc_space);
6251 }
6252 
6253 static int
6254 load_unflushed_cb(spa_t *spa, space_map_entry_t *sme, uint64_t txg, void *arg)
6255 {
6256 	maptype_t *uic_maptype = arg;
6257 
6258 	uint64_t offset = sme->sme_offset;
6259 	uint64_t size = sme->sme_run;
6260 	uint64_t vdev_id = sme->sme_vdev;
6261 
6262 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
6263 
6264 	/* skip indirect vdevs */
6265 	if (!vdev_is_concrete(vd))
6266 		return (0);
6267 
6268 	metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
6269 
6270 	ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
6271 	ASSERT(*uic_maptype == SM_ALLOC || *uic_maptype == SM_FREE);
6272 
6273 	if (txg < metaslab_unflushed_txg(ms))
6274 		return (0);
6275 
6276 	if (*uic_maptype == sme->sme_type)
6277 		range_tree_add(ms->ms_allocatable, offset, size);
6278 	else
6279 		range_tree_remove(ms->ms_allocatable, offset, size);
6280 
6281 	return (0);
6282 }
6283 
6284 static void
6285 load_unflushed_to_ms_allocatables(spa_t *spa, maptype_t maptype)
6286 {
6287 	iterate_through_spacemap_logs(spa, load_unflushed_cb, &maptype);
6288 }
6289 
6290 static void
6291 load_concrete_ms_allocatable_trees(spa_t *spa, maptype_t maptype)
6292 {
6293 	vdev_t *rvd = spa->spa_root_vdev;
6294 	for (uint64_t i = 0; i < rvd->vdev_children; i++) {
6295 		vdev_t *vd = rvd->vdev_child[i];
6296 
6297 		ASSERT3U(i, ==, vd->vdev_id);
6298 
6299 		if (vd->vdev_ops == &vdev_indirect_ops)
6300 			continue;
6301 
6302 		for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
6303 			metaslab_t *msp = vd->vdev_ms[m];
6304 
6305 			(void) fprintf(stderr,
6306 			    "\rloading concrete vdev %llu, "
6307 			    "metaslab %llu of %llu ...",
6308 			    (longlong_t)vd->vdev_id,
6309 			    (longlong_t)msp->ms_id,
6310 			    (longlong_t)vd->vdev_ms_count);
6311 
6312 			mutex_enter(&msp->ms_lock);
6313 			range_tree_vacate(msp->ms_allocatable, NULL, NULL);
6314 
6315 			/*
6316 			 * We don't want to spend the CPU manipulating the
6317 			 * size-ordered tree, so clear the range_tree ops.
6318 			 */
6319 			msp->ms_allocatable->rt_ops = NULL;
6320 
6321 			if (msp->ms_sm != NULL) {
6322 				VERIFY0(space_map_load(msp->ms_sm,
6323 				    msp->ms_allocatable, maptype));
6324 			}
6325 			if (!msp->ms_loaded)
6326 				msp->ms_loaded = B_TRUE;
6327 			mutex_exit(&msp->ms_lock);
6328 		}
6329 	}
6330 
6331 	load_unflushed_to_ms_allocatables(spa, maptype);
6332 }
6333 
6334 /*
6335  * vm_idxp is an in-out parameter which (for indirect vdevs) is the
6336  * index in vim_entries that has the first entry in this metaslab.
6337  * On return, it will be set to the first entry after this metaslab.
6338  */
6339 static void
6340 load_indirect_ms_allocatable_tree(vdev_t *vd, metaslab_t *msp,
6341     uint64_t *vim_idxp)
6342 {
6343 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6344 
6345 	mutex_enter(&msp->ms_lock);
6346 	range_tree_vacate(msp->ms_allocatable, NULL, NULL);
6347 
6348 	/*
6349 	 * We don't want to spend the CPU manipulating the
6350 	 * size-ordered tree, so clear the range_tree ops.
6351 	 */
6352 	msp->ms_allocatable->rt_ops = NULL;
6353 
6354 	for (; *vim_idxp < vdev_indirect_mapping_num_entries(vim);
6355 	    (*vim_idxp)++) {
6356 		vdev_indirect_mapping_entry_phys_t *vimep =
6357 		    &vim->vim_entries[*vim_idxp];
6358 		uint64_t ent_offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
6359 		uint64_t ent_len = DVA_GET_ASIZE(&vimep->vimep_dst);
6360 		ASSERT3U(ent_offset, >=, msp->ms_start);
6361 		if (ent_offset >= msp->ms_start + msp->ms_size)
6362 			break;
6363 
6364 		/*
6365 		 * Mappings do not cross metaslab boundaries,
6366 		 * because we create them by walking the metaslabs.
6367 		 */
6368 		ASSERT3U(ent_offset + ent_len, <=,
6369 		    msp->ms_start + msp->ms_size);
6370 		range_tree_add(msp->ms_allocatable, ent_offset, ent_len);
6371 	}
6372 
6373 	if (!msp->ms_loaded)
6374 		msp->ms_loaded = B_TRUE;
6375 	mutex_exit(&msp->ms_lock);
6376 }
6377 
6378 static void
6379 zdb_leak_init_prepare_indirect_vdevs(spa_t *spa, zdb_cb_t *zcb)
6380 {
6381 	ASSERT(!dump_opt['L']);
6382 
6383 	vdev_t *rvd = spa->spa_root_vdev;
6384 	for (uint64_t c = 0; c < rvd->vdev_children; c++) {
6385 		vdev_t *vd = rvd->vdev_child[c];
6386 
6387 		ASSERT3U(c, ==, vd->vdev_id);
6388 
6389 		if (vd->vdev_ops != &vdev_indirect_ops)
6390 			continue;
6391 
6392 		/*
6393 		 * Note: we don't check for mapping leaks on
6394 		 * removing vdevs because their ms_allocatable's
6395 		 * are used to look for leaks in allocated space.
6396 		 */
6397 		zcb->zcb_vd_obsolete_counts[c] = zdb_load_obsolete_counts(vd);
6398 
6399 		/*
6400 		 * Normally, indirect vdevs don't have any
6401 		 * metaslabs.  We want to set them up for
6402 		 * zio_claim().
6403 		 */
6404 		vdev_metaslab_group_create(vd);
6405 		VERIFY0(vdev_metaslab_init(vd, 0));
6406 
6407 		vdev_indirect_mapping_t *vim __maybe_unused =
6408 		    vd->vdev_indirect_mapping;
6409 		uint64_t vim_idx = 0;
6410 		for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
6411 
6412 			(void) fprintf(stderr,
6413 			    "\rloading indirect vdev %llu, "
6414 			    "metaslab %llu of %llu ...",
6415 			    (longlong_t)vd->vdev_id,
6416 			    (longlong_t)vd->vdev_ms[m]->ms_id,
6417 			    (longlong_t)vd->vdev_ms_count);
6418 
6419 			load_indirect_ms_allocatable_tree(vd, vd->vdev_ms[m],
6420 			    &vim_idx);
6421 		}
6422 		ASSERT3U(vim_idx, ==, vdev_indirect_mapping_num_entries(vim));
6423 	}
6424 }
6425 
6426 static void
6427 zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
6428 {
6429 	zcb->zcb_spa = spa;
6430 
6431 	if (dump_opt['L'])
6432 		return;
6433 
6434 	dsl_pool_t *dp = spa->spa_dsl_pool;
6435 	vdev_t *rvd = spa->spa_root_vdev;
6436 
6437 	/*
6438 	 * We are going to be changing the meaning of the metaslab's
6439 	 * ms_allocatable.  Ensure that the allocator doesn't try to
6440 	 * use the tree.
6441 	 */
6442 	spa->spa_normal_class->mc_ops = &zdb_metaslab_ops;
6443 	spa->spa_log_class->mc_ops = &zdb_metaslab_ops;
6444 	spa->spa_embedded_log_class->mc_ops = &zdb_metaslab_ops;
6445 
6446 	zcb->zcb_vd_obsolete_counts =
6447 	    umem_zalloc(rvd->vdev_children * sizeof (uint32_t *),
6448 	    UMEM_NOFAIL);
6449 
6450 	/*
6451 	 * For leak detection, we overload the ms_allocatable trees
6452 	 * to contain allocated segments instead of free segments.
6453 	 * As a result, we can't use the normal metaslab_load/unload
6454 	 * interfaces.
6455 	 */
6456 	zdb_leak_init_prepare_indirect_vdevs(spa, zcb);
6457 	load_concrete_ms_allocatable_trees(spa, SM_ALLOC);
6458 
6459 	/*
6460 	 * On load_concrete_ms_allocatable_trees() we loaded all the
6461 	 * allocated entries from the ms_sm to the ms_allocatable for
6462 	 * each metaslab. If the pool has a checkpoint or is in the
6463 	 * middle of discarding a checkpoint, some of these blocks
6464 	 * may have been freed but their ms_sm may not have been
6465 	 * updated because they are referenced by the checkpoint. In
6466 	 * order to avoid false-positives during leak-detection, we
6467 	 * go through the vdev's checkpoint space map and exclude all
6468 	 * its entries from their relevant ms_allocatable.
6469 	 *
6470 	 * We also aggregate the space held by the checkpoint and add
6471 	 * it to zcb_checkpoint_size.
6472 	 *
6473 	 * Note that at this point we are also verifying that all the
6474 	 * entries on the checkpoint_sm are marked as allocated in
6475 	 * the ms_sm of their relevant metaslab.
6476 	 * [see comment in checkpoint_sm_exclude_entry_cb()]
6477 	 */
6478 	zdb_leak_init_exclude_checkpoint(spa, zcb);
6479 	ASSERT3U(zcb->zcb_checkpoint_size, ==, spa_get_checkpoint_space(spa));
6480 
6481 	/* for cleaner progress output */
6482 	(void) fprintf(stderr, "\n");
6483 
6484 	if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
6485 		ASSERT(spa_feature_is_enabled(spa,
6486 		    SPA_FEATURE_DEVICE_REMOVAL));
6487 		(void) bpobj_iterate_nofree(&dp->dp_obsolete_bpobj,
6488 		    increment_indirect_mapping_cb, zcb, NULL);
6489 	}
6490 
6491 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6492 	zdb_ddt_leak_init(spa, zcb);
6493 	spa_config_exit(spa, SCL_CONFIG, FTAG);
6494 }
6495 
6496 static boolean_t
6497 zdb_check_for_obsolete_leaks(vdev_t *vd, zdb_cb_t *zcb)
6498 {
6499 	boolean_t leaks = B_FALSE;
6500 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6501 	uint64_t total_leaked = 0;
6502 	boolean_t are_precise = B_FALSE;
6503 
6504 	ASSERT(vim != NULL);
6505 
6506 	for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
6507 		vdev_indirect_mapping_entry_phys_t *vimep =
6508 		    &vim->vim_entries[i];
6509 		uint64_t obsolete_bytes = 0;
6510 		uint64_t offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
6511 		metaslab_t *msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
6512 
6513 		/*
6514 		 * This is not very efficient but it's easy to
6515 		 * verify correctness.
6516 		 */
6517 		for (uint64_t inner_offset = 0;
6518 		    inner_offset < DVA_GET_ASIZE(&vimep->vimep_dst);
6519 		    inner_offset += 1ULL << vd->vdev_ashift) {
6520 			if (range_tree_contains(msp->ms_allocatable,
6521 			    offset + inner_offset, 1ULL << vd->vdev_ashift)) {
6522 				obsolete_bytes += 1ULL << vd->vdev_ashift;
6523 			}
6524 		}
6525 
6526 		int64_t bytes_leaked = obsolete_bytes -
6527 		    zcb->zcb_vd_obsolete_counts[vd->vdev_id][i];
6528 		ASSERT3U(DVA_GET_ASIZE(&vimep->vimep_dst), >=,
6529 		    zcb->zcb_vd_obsolete_counts[vd->vdev_id][i]);
6530 
6531 		VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
6532 		if (bytes_leaked != 0 && (are_precise || dump_opt['d'] >= 5)) {
6533 			(void) printf("obsolete indirect mapping count "
6534 			    "mismatch on %llu:%llx:%llx : %llx bytes leaked\n",
6535 			    (u_longlong_t)vd->vdev_id,
6536 			    (u_longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
6537 			    (u_longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
6538 			    (u_longlong_t)bytes_leaked);
6539 		}
6540 		total_leaked += ABS(bytes_leaked);
6541 	}
6542 
6543 	VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
6544 	if (!are_precise && total_leaked > 0) {
6545 		int pct_leaked = total_leaked * 100 /
6546 		    vdev_indirect_mapping_bytes_mapped(vim);
6547 		(void) printf("cannot verify obsolete indirect mapping "
6548 		    "counts of vdev %llu because precise feature was not "
6549 		    "enabled when it was removed: %d%% (%llx bytes) of mapping"
6550 		    "unreferenced\n",
6551 		    (u_longlong_t)vd->vdev_id, pct_leaked,
6552 		    (u_longlong_t)total_leaked);
6553 	} else if (total_leaked > 0) {
6554 		(void) printf("obsolete indirect mapping count mismatch "
6555 		    "for vdev %llu -- %llx total bytes mismatched\n",
6556 		    (u_longlong_t)vd->vdev_id,
6557 		    (u_longlong_t)total_leaked);
6558 		leaks |= B_TRUE;
6559 	}
6560 
6561 	vdev_indirect_mapping_free_obsolete_counts(vim,
6562 	    zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
6563 	zcb->zcb_vd_obsolete_counts[vd->vdev_id] = NULL;
6564 
6565 	return (leaks);
6566 }
6567 
6568 static boolean_t
6569 zdb_leak_fini(spa_t *spa, zdb_cb_t *zcb)
6570 {
6571 	if (dump_opt['L'])
6572 		return (B_FALSE);
6573 
6574 	boolean_t leaks = B_FALSE;
6575 	vdev_t *rvd = spa->spa_root_vdev;
6576 	for (unsigned c = 0; c < rvd->vdev_children; c++) {
6577 		vdev_t *vd = rvd->vdev_child[c];
6578 
6579 		if (zcb->zcb_vd_obsolete_counts[c] != NULL) {
6580 			leaks |= zdb_check_for_obsolete_leaks(vd, zcb);
6581 		}
6582 
6583 		for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
6584 			metaslab_t *msp = vd->vdev_ms[m];
6585 			ASSERT3P(msp->ms_group, ==, (msp->ms_group->mg_class ==
6586 			    spa_embedded_log_class(spa)) ?
6587 			    vd->vdev_log_mg : vd->vdev_mg);
6588 
6589 			/*
6590 			 * ms_allocatable has been overloaded
6591 			 * to contain allocated segments. Now that
6592 			 * we finished traversing all blocks, any
6593 			 * block that remains in the ms_allocatable
6594 			 * represents an allocated block that we
6595 			 * did not claim during the traversal.
6596 			 * Claimed blocks would have been removed
6597 			 * from the ms_allocatable.  For indirect
6598 			 * vdevs, space remaining in the tree
6599 			 * represents parts of the mapping that are
6600 			 * not referenced, which is not a bug.
6601 			 */
6602 			if (vd->vdev_ops == &vdev_indirect_ops) {
6603 				range_tree_vacate(msp->ms_allocatable,
6604 				    NULL, NULL);
6605 			} else {
6606 				range_tree_vacate(msp->ms_allocatable,
6607 				    zdb_leak, vd);
6608 			}
6609 			if (msp->ms_loaded) {
6610 				msp->ms_loaded = B_FALSE;
6611 			}
6612 		}
6613 	}
6614 
6615 	umem_free(zcb->zcb_vd_obsolete_counts,
6616 	    rvd->vdev_children * sizeof (uint32_t *));
6617 	zcb->zcb_vd_obsolete_counts = NULL;
6618 
6619 	return (leaks);
6620 }
6621 
6622 static int
6623 count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
6624 {
6625 	(void) tx;
6626 	zdb_cb_t *zcb = arg;
6627 
6628 	if (dump_opt['b'] >= 5) {
6629 		char blkbuf[BP_SPRINTF_LEN];
6630 		snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
6631 		(void) printf("[%s] %s\n",
6632 		    "deferred free", blkbuf);
6633 	}
6634 	zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
6635 	return (0);
6636 }
6637 
6638 /*
6639  * Iterate over livelists which have been destroyed by the user but
6640  * are still present in the MOS, waiting to be freed
6641  */
6642 static void
6643 iterate_deleted_livelists(spa_t *spa, ll_iter_t func, void *arg)
6644 {
6645 	objset_t *mos = spa->spa_meta_objset;
6646 	uint64_t zap_obj;
6647 	int err = zap_lookup(mos, DMU_POOL_DIRECTORY_OBJECT,
6648 	    DMU_POOL_DELETED_CLONES, sizeof (uint64_t), 1, &zap_obj);
6649 	if (err == ENOENT)
6650 		return;
6651 	ASSERT0(err);
6652 
6653 	zap_cursor_t zc;
6654 	zap_attribute_t attr;
6655 	dsl_deadlist_t ll;
6656 	/* NULL out os prior to dsl_deadlist_open in case it's garbage */
6657 	ll.dl_os = NULL;
6658 	for (zap_cursor_init(&zc, mos, zap_obj);
6659 	    zap_cursor_retrieve(&zc, &attr) == 0;
6660 	    (void) zap_cursor_advance(&zc)) {
6661 		dsl_deadlist_open(&ll, mos, attr.za_first_integer);
6662 		func(&ll, arg);
6663 		dsl_deadlist_close(&ll);
6664 	}
6665 	zap_cursor_fini(&zc);
6666 }
6667 
6668 static int
6669 bpobj_count_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
6670     dmu_tx_t *tx)
6671 {
6672 	ASSERT(!bp_freed);
6673 	return (count_block_cb(arg, bp, tx));
6674 }
6675 
6676 static int
6677 livelist_entry_count_blocks_cb(void *args, dsl_deadlist_entry_t *dle)
6678 {
6679 	zdb_cb_t *zbc = args;
6680 	bplist_t blks;
6681 	bplist_create(&blks);
6682 	/* determine which blocks have been alloc'd but not freed */
6683 	VERIFY0(dsl_process_sub_livelist(&dle->dle_bpobj, &blks, NULL, NULL));
6684 	/* count those blocks */
6685 	(void) bplist_iterate(&blks, count_block_cb, zbc, NULL);
6686 	bplist_destroy(&blks);
6687 	return (0);
6688 }
6689 
6690 static void
6691 livelist_count_blocks(dsl_deadlist_t *ll, void *arg)
6692 {
6693 	dsl_deadlist_iterate(ll, livelist_entry_count_blocks_cb, arg);
6694 }
6695 
6696 /*
6697  * Count the blocks in the livelists that have been destroyed by the user
6698  * but haven't yet been freed.
6699  */
6700 static void
6701 deleted_livelists_count_blocks(spa_t *spa, zdb_cb_t *zbc)
6702 {
6703 	iterate_deleted_livelists(spa, livelist_count_blocks, zbc);
6704 }
6705 
6706 static void
6707 dump_livelist_cb(dsl_deadlist_t *ll, void *arg)
6708 {
6709 	ASSERT3P(arg, ==, NULL);
6710 	global_feature_count[SPA_FEATURE_LIVELIST]++;
6711 	dump_blkptr_list(ll, "Deleted Livelist");
6712 	dsl_deadlist_iterate(ll, sublivelist_verify_lightweight, NULL);
6713 }
6714 
6715 /*
6716  * Print out, register object references to, and increment feature counts for
6717  * livelists that have been destroyed by the user but haven't yet been freed.
6718  */
6719 static void
6720 deleted_livelists_dump_mos(spa_t *spa)
6721 {
6722 	uint64_t zap_obj;
6723 	objset_t *mos = spa->spa_meta_objset;
6724 	int err = zap_lookup(mos, DMU_POOL_DIRECTORY_OBJECT,
6725 	    DMU_POOL_DELETED_CLONES, sizeof (uint64_t), 1, &zap_obj);
6726 	if (err == ENOENT)
6727 		return;
6728 	mos_obj_refd(zap_obj);
6729 	iterate_deleted_livelists(spa, dump_livelist_cb, NULL);
6730 }
6731 
6732 static int
6733 zdb_brt_entry_compare(const void *zcn1, const void *zcn2)
6734 {
6735 	const dva_t *dva1 = &((const zdb_brt_entry_t *)zcn1)->zbre_dva;
6736 	const dva_t *dva2 = &((const zdb_brt_entry_t *)zcn2)->zbre_dva;
6737 	int cmp;
6738 
6739 	cmp = TREE_CMP(DVA_GET_VDEV(dva1), DVA_GET_VDEV(dva2));
6740 	if (cmp == 0)
6741 		cmp = TREE_CMP(DVA_GET_OFFSET(dva1), DVA_GET_OFFSET(dva2));
6742 
6743 	return (cmp);
6744 }
6745 
6746 static int
6747 dump_block_stats(spa_t *spa)
6748 {
6749 	zdb_cb_t *zcb;
6750 	zdb_blkstats_t *zb, *tzb;
6751 	uint64_t norm_alloc, norm_space, total_alloc, total_found;
6752 	int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
6753 	    TRAVERSE_NO_DECRYPT | TRAVERSE_HARD;
6754 	boolean_t leaks = B_FALSE;
6755 	int e, c, err;
6756 	bp_embedded_type_t i;
6757 
6758 	zcb = umem_zalloc(sizeof (zdb_cb_t), UMEM_NOFAIL);
6759 
6760 	if (spa_feature_is_active(spa, SPA_FEATURE_BLOCK_CLONING)) {
6761 		avl_create(&zcb->zcb_brt, zdb_brt_entry_compare,
6762 		    sizeof (zdb_brt_entry_t),
6763 		    offsetof(zdb_brt_entry_t, zbre_node));
6764 		zcb->zcb_brt_is_active = B_TRUE;
6765 	}
6766 
6767 	(void) printf("\nTraversing all blocks %s%s%s%s%s...\n\n",
6768 	    (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
6769 	    (dump_opt['c'] == 1) ? "metadata " : "",
6770 	    dump_opt['c'] ? "checksums " : "",
6771 	    (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
6772 	    !dump_opt['L'] ? "nothing leaked " : "");
6773 
6774 	/*
6775 	 * When leak detection is enabled we load all space maps as SM_ALLOC
6776 	 * maps, then traverse the pool claiming each block we discover. If
6777 	 * the pool is perfectly consistent, the segment trees will be empty
6778 	 * when we're done. Anything left over is a leak; any block we can't
6779 	 * claim (because it's not part of any space map) is a double
6780 	 * allocation, reference to a freed block, or an unclaimed log block.
6781 	 *
6782 	 * When leak detection is disabled (-L option) we still traverse the
6783 	 * pool claiming each block we discover, but we skip opening any space
6784 	 * maps.
6785 	 */
6786 	zdb_leak_init(spa, zcb);
6787 
6788 	/*
6789 	 * If there's a deferred-free bplist, process that first.
6790 	 */
6791 	(void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
6792 	    bpobj_count_block_cb, zcb, NULL);
6793 
6794 	if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
6795 		(void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
6796 		    bpobj_count_block_cb, zcb, NULL);
6797 	}
6798 
6799 	zdb_claim_removing(spa, zcb);
6800 
6801 	if (spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
6802 		VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
6803 		    spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
6804 		    zcb, NULL));
6805 	}
6806 
6807 	deleted_livelists_count_blocks(spa, zcb);
6808 
6809 	if (dump_opt['c'] > 1)
6810 		flags |= TRAVERSE_PREFETCH_DATA;
6811 
6812 	zcb->zcb_totalasize = metaslab_class_get_alloc(spa_normal_class(spa));
6813 	zcb->zcb_totalasize += metaslab_class_get_alloc(spa_special_class(spa));
6814 	zcb->zcb_totalasize += metaslab_class_get_alloc(spa_dedup_class(spa));
6815 	zcb->zcb_totalasize +=
6816 	    metaslab_class_get_alloc(spa_embedded_log_class(spa));
6817 	zcb->zcb_start = zcb->zcb_lastprint = gethrtime();
6818 	err = traverse_pool(spa, 0, flags, zdb_blkptr_cb, zcb);
6819 
6820 	/*
6821 	 * If we've traversed the data blocks then we need to wait for those
6822 	 * I/Os to complete. We leverage "The Godfather" zio to wait on
6823 	 * all async I/Os to complete.
6824 	 */
6825 	if (dump_opt['c']) {
6826 		for (c = 0; c < max_ncpus; c++) {
6827 			(void) zio_wait(spa->spa_async_zio_root[c]);
6828 			spa->spa_async_zio_root[c] = zio_root(spa, NULL, NULL,
6829 			    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
6830 			    ZIO_FLAG_GODFATHER);
6831 		}
6832 	}
6833 	ASSERT0(spa->spa_load_verify_bytes);
6834 
6835 	/*
6836 	 * Done after zio_wait() since zcb_haderrors is modified in
6837 	 * zdb_blkptr_done()
6838 	 */
6839 	zcb->zcb_haderrors |= err;
6840 
6841 	if (zcb->zcb_haderrors) {
6842 		(void) printf("\nError counts:\n\n");
6843 		(void) printf("\t%5s  %s\n", "errno", "count");
6844 		for (e = 0; e < 256; e++) {
6845 			if (zcb->zcb_errors[e] != 0) {
6846 				(void) printf("\t%5d  %llu\n",
6847 				    e, (u_longlong_t)zcb->zcb_errors[e]);
6848 			}
6849 		}
6850 	}
6851 
6852 	/*
6853 	 * Report any leaked segments.
6854 	 */
6855 	leaks |= zdb_leak_fini(spa, zcb);
6856 
6857 	tzb = &zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
6858 
6859 	norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
6860 	norm_space = metaslab_class_get_space(spa_normal_class(spa));
6861 
6862 	total_alloc = norm_alloc +
6863 	    metaslab_class_get_alloc(spa_log_class(spa)) +
6864 	    metaslab_class_get_alloc(spa_embedded_log_class(spa)) +
6865 	    metaslab_class_get_alloc(spa_special_class(spa)) +
6866 	    metaslab_class_get_alloc(spa_dedup_class(spa)) +
6867 	    get_unflushed_alloc_space(spa);
6868 	total_found =
6869 	    tzb->zb_asize - zcb->zcb_dedup_asize - zcb->zcb_clone_asize +
6870 	    zcb->zcb_removing_size + zcb->zcb_checkpoint_size;
6871 
6872 	if (total_found == total_alloc && !dump_opt['L']) {
6873 		(void) printf("\n\tNo leaks (block sum matches space"
6874 		    " maps exactly)\n");
6875 	} else if (!dump_opt['L']) {
6876 		(void) printf("block traversal size %llu != alloc %llu "
6877 		    "(%s %lld)\n",
6878 		    (u_longlong_t)total_found,
6879 		    (u_longlong_t)total_alloc,
6880 		    (dump_opt['L']) ? "unreachable" : "leaked",
6881 		    (longlong_t)(total_alloc - total_found));
6882 		leaks = B_TRUE;
6883 	}
6884 
6885 	if (tzb->zb_count == 0) {
6886 		umem_free(zcb, sizeof (zdb_cb_t));
6887 		return (2);
6888 	}
6889 
6890 	(void) printf("\n");
6891 	(void) printf("\t%-16s %14llu\n", "bp count:",
6892 	    (u_longlong_t)tzb->zb_count);
6893 	(void) printf("\t%-16s %14llu\n", "ganged count:",
6894 	    (longlong_t)tzb->zb_gangs);
6895 	(void) printf("\t%-16s %14llu      avg: %6llu\n", "bp logical:",
6896 	    (u_longlong_t)tzb->zb_lsize,
6897 	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
6898 	(void) printf("\t%-16s %14llu      avg: %6llu     compression: %6.2f\n",
6899 	    "bp physical:", (u_longlong_t)tzb->zb_psize,
6900 	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
6901 	    (double)tzb->zb_lsize / tzb->zb_psize);
6902 	(void) printf("\t%-16s %14llu      avg: %6llu     compression: %6.2f\n",
6903 	    "bp allocated:", (u_longlong_t)tzb->zb_asize,
6904 	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
6905 	    (double)tzb->zb_lsize / tzb->zb_asize);
6906 	(void) printf("\t%-16s %14llu    ref>1: %6llu   deduplication: %6.2f\n",
6907 	    "bp deduped:", (u_longlong_t)zcb->zcb_dedup_asize,
6908 	    (u_longlong_t)zcb->zcb_dedup_blocks,
6909 	    (double)zcb->zcb_dedup_asize / tzb->zb_asize + 1.0);
6910 	(void) printf("\t%-16s %14llu    count: %6llu\n",
6911 	    "bp cloned:", (u_longlong_t)zcb->zcb_clone_asize,
6912 	    (u_longlong_t)zcb->zcb_clone_blocks);
6913 	(void) printf("\t%-16s %14llu     used: %5.2f%%\n", "Normal class:",
6914 	    (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
6915 
6916 	if (spa_special_class(spa)->mc_allocator[0].mca_rotor != NULL) {
6917 		uint64_t alloc = metaslab_class_get_alloc(
6918 		    spa_special_class(spa));
6919 		uint64_t space = metaslab_class_get_space(
6920 		    spa_special_class(spa));
6921 
6922 		(void) printf("\t%-16s %14llu     used: %5.2f%%\n",
6923 		    "Special class", (u_longlong_t)alloc,
6924 		    100.0 * alloc / space);
6925 	}
6926 
6927 	if (spa_dedup_class(spa)->mc_allocator[0].mca_rotor != NULL) {
6928 		uint64_t alloc = metaslab_class_get_alloc(
6929 		    spa_dedup_class(spa));
6930 		uint64_t space = metaslab_class_get_space(
6931 		    spa_dedup_class(spa));
6932 
6933 		(void) printf("\t%-16s %14llu     used: %5.2f%%\n",
6934 		    "Dedup class", (u_longlong_t)alloc,
6935 		    100.0 * alloc / space);
6936 	}
6937 
6938 	if (spa_embedded_log_class(spa)->mc_allocator[0].mca_rotor != NULL) {
6939 		uint64_t alloc = metaslab_class_get_alloc(
6940 		    spa_embedded_log_class(spa));
6941 		uint64_t space = metaslab_class_get_space(
6942 		    spa_embedded_log_class(spa));
6943 
6944 		(void) printf("\t%-16s %14llu     used: %5.2f%%\n",
6945 		    "Embedded log class", (u_longlong_t)alloc,
6946 		    100.0 * alloc / space);
6947 	}
6948 
6949 	for (i = 0; i < NUM_BP_EMBEDDED_TYPES; i++) {
6950 		if (zcb->zcb_embedded_blocks[i] == 0)
6951 			continue;
6952 		(void) printf("\n");
6953 		(void) printf("\tadditional, non-pointer bps of type %u: "
6954 		    "%10llu\n",
6955 		    i, (u_longlong_t)zcb->zcb_embedded_blocks[i]);
6956 
6957 		if (dump_opt['b'] >= 3) {
6958 			(void) printf("\t number of (compressed) bytes:  "
6959 			    "number of bps\n");
6960 			dump_histogram(zcb->zcb_embedded_histogram[i],
6961 			    sizeof (zcb->zcb_embedded_histogram[i]) /
6962 			    sizeof (zcb->zcb_embedded_histogram[i][0]), 0);
6963 		}
6964 	}
6965 
6966 	if (tzb->zb_ditto_samevdev != 0) {
6967 		(void) printf("\tDittoed blocks on same vdev: %llu\n",
6968 		    (longlong_t)tzb->zb_ditto_samevdev);
6969 	}
6970 	if (tzb->zb_ditto_same_ms != 0) {
6971 		(void) printf("\tDittoed blocks in same metaslab: %llu\n",
6972 		    (longlong_t)tzb->zb_ditto_same_ms);
6973 	}
6974 
6975 	for (uint64_t v = 0; v < spa->spa_root_vdev->vdev_children; v++) {
6976 		vdev_t *vd = spa->spa_root_vdev->vdev_child[v];
6977 		vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6978 
6979 		if (vim == NULL) {
6980 			continue;
6981 		}
6982 
6983 		char mem[32];
6984 		zdb_nicenum(vdev_indirect_mapping_num_entries(vim),
6985 		    mem, vdev_indirect_mapping_size(vim));
6986 
6987 		(void) printf("\tindirect vdev id %llu has %llu segments "
6988 		    "(%s in memory)\n",
6989 		    (longlong_t)vd->vdev_id,
6990 		    (longlong_t)vdev_indirect_mapping_num_entries(vim), mem);
6991 	}
6992 
6993 	if (dump_opt['b'] >= 2) {
6994 		int l, t, level;
6995 		char csize[32], lsize[32], psize[32], asize[32];
6996 		char avg[32], gang[32];
6997 		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
6998 		    "\t  avg\t comp\t%%Total\tType\n");
6999 
7000 		zfs_blkstat_t *mdstats = umem_zalloc(sizeof (zfs_blkstat_t),
7001 		    UMEM_NOFAIL);
7002 
7003 		for (t = 0; t <= ZDB_OT_TOTAL; t++) {
7004 			const char *typename;
7005 
7006 			/* make sure nicenum has enough space */
7007 			_Static_assert(sizeof (csize) >= NN_NUMBUF_SZ,
7008 			    "csize truncated");
7009 			_Static_assert(sizeof (lsize) >= NN_NUMBUF_SZ,
7010 			    "lsize truncated");
7011 			_Static_assert(sizeof (psize) >= NN_NUMBUF_SZ,
7012 			    "psize truncated");
7013 			_Static_assert(sizeof (asize) >= NN_NUMBUF_SZ,
7014 			    "asize truncated");
7015 			_Static_assert(sizeof (avg) >= NN_NUMBUF_SZ,
7016 			    "avg truncated");
7017 			_Static_assert(sizeof (gang) >= NN_NUMBUF_SZ,
7018 			    "gang truncated");
7019 
7020 			if (t < DMU_OT_NUMTYPES)
7021 				typename = dmu_ot[t].ot_name;
7022 			else
7023 				typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
7024 
7025 			if (zcb->zcb_type[ZB_TOTAL][t].zb_asize == 0) {
7026 				(void) printf("%6s\t%5s\t%5s\t%5s"
7027 				    "\t%5s\t%5s\t%6s\t%s\n",
7028 				    "-",
7029 				    "-",
7030 				    "-",
7031 				    "-",
7032 				    "-",
7033 				    "-",
7034 				    "-",
7035 				    typename);
7036 				continue;
7037 			}
7038 
7039 			for (l = ZB_TOTAL - 1; l >= -1; l--) {
7040 				level = (l == -1 ? ZB_TOTAL : l);
7041 				zb = &zcb->zcb_type[level][t];
7042 
7043 				if (zb->zb_asize == 0)
7044 					continue;
7045 
7046 				if (level != ZB_TOTAL && t < DMU_OT_NUMTYPES &&
7047 				    (level > 0 || DMU_OT_IS_METADATA(t))) {
7048 					mdstats->zb_count += zb->zb_count;
7049 					mdstats->zb_lsize += zb->zb_lsize;
7050 					mdstats->zb_psize += zb->zb_psize;
7051 					mdstats->zb_asize += zb->zb_asize;
7052 					mdstats->zb_gangs += zb->zb_gangs;
7053 				}
7054 
7055 				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
7056 					continue;
7057 
7058 				if (level == 0 && zb->zb_asize ==
7059 				    zcb->zcb_type[ZB_TOTAL][t].zb_asize)
7060 					continue;
7061 
7062 				zdb_nicenum(zb->zb_count, csize,
7063 				    sizeof (csize));
7064 				zdb_nicenum(zb->zb_lsize, lsize,
7065 				    sizeof (lsize));
7066 				zdb_nicenum(zb->zb_psize, psize,
7067 				    sizeof (psize));
7068 				zdb_nicenum(zb->zb_asize, asize,
7069 				    sizeof (asize));
7070 				zdb_nicenum(zb->zb_asize / zb->zb_count, avg,
7071 				    sizeof (avg));
7072 				zdb_nicenum(zb->zb_gangs, gang, sizeof (gang));
7073 
7074 				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
7075 				    "\t%5.2f\t%6.2f\t",
7076 				    csize, lsize, psize, asize, avg,
7077 				    (double)zb->zb_lsize / zb->zb_psize,
7078 				    100.0 * zb->zb_asize / tzb->zb_asize);
7079 
7080 				if (level == ZB_TOTAL)
7081 					(void) printf("%s\n", typename);
7082 				else
7083 					(void) printf("    L%d %s\n",
7084 					    level, typename);
7085 
7086 				if (dump_opt['b'] >= 3 && zb->zb_gangs > 0) {
7087 					(void) printf("\t number of ganged "
7088 					    "blocks: %s\n", gang);
7089 				}
7090 
7091 				if (dump_opt['b'] >= 4) {
7092 					(void) printf("psize "
7093 					    "(in 512-byte sectors): "
7094 					    "number of blocks\n");
7095 					dump_histogram(zb->zb_psize_histogram,
7096 					    PSIZE_HISTO_SIZE, 0);
7097 				}
7098 			}
7099 		}
7100 		zdb_nicenum(mdstats->zb_count, csize,
7101 		    sizeof (csize));
7102 		zdb_nicenum(mdstats->zb_lsize, lsize,
7103 		    sizeof (lsize));
7104 		zdb_nicenum(mdstats->zb_psize, psize,
7105 		    sizeof (psize));
7106 		zdb_nicenum(mdstats->zb_asize, asize,
7107 		    sizeof (asize));
7108 		zdb_nicenum(mdstats->zb_asize / mdstats->zb_count, avg,
7109 		    sizeof (avg));
7110 		zdb_nicenum(mdstats->zb_gangs, gang, sizeof (gang));
7111 
7112 		(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
7113 		    "\t%5.2f\t%6.2f\t",
7114 		    csize, lsize, psize, asize, avg,
7115 		    (double)mdstats->zb_lsize / mdstats->zb_psize,
7116 		    100.0 * mdstats->zb_asize / tzb->zb_asize);
7117 		(void) printf("%s\n", "Metadata Total");
7118 
7119 		/* Output a table summarizing block sizes in the pool */
7120 		if (dump_opt['b'] >= 2) {
7121 			dump_size_histograms(zcb);
7122 		}
7123 
7124 		umem_free(mdstats, sizeof (zfs_blkstat_t));
7125 	}
7126 
7127 	(void) printf("\n");
7128 
7129 	if (leaks) {
7130 		umem_free(zcb, sizeof (zdb_cb_t));
7131 		return (2);
7132 	}
7133 
7134 	if (zcb->zcb_haderrors) {
7135 		umem_free(zcb, sizeof (zdb_cb_t));
7136 		return (3);
7137 	}
7138 
7139 	umem_free(zcb, sizeof (zdb_cb_t));
7140 	return (0);
7141 }
7142 
7143 typedef struct zdb_ddt_entry {
7144 	ddt_key_t	zdde_key;
7145 	uint64_t	zdde_ref_blocks;
7146 	uint64_t	zdde_ref_lsize;
7147 	uint64_t	zdde_ref_psize;
7148 	uint64_t	zdde_ref_dsize;
7149 	avl_node_t	zdde_node;
7150 } zdb_ddt_entry_t;
7151 
7152 static int
7153 zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
7154     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
7155 {
7156 	(void) zilog, (void) dnp;
7157 	avl_tree_t *t = arg;
7158 	avl_index_t where;
7159 	zdb_ddt_entry_t *zdde, zdde_search;
7160 
7161 	if (zb->zb_level == ZB_DNODE_LEVEL || BP_IS_HOLE(bp) ||
7162 	    BP_IS_EMBEDDED(bp))
7163 		return (0);
7164 
7165 	if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
7166 		(void) printf("traversing objset %llu, %llu objects, "
7167 		    "%lu blocks so far\n",
7168 		    (u_longlong_t)zb->zb_objset,
7169 		    (u_longlong_t)BP_GET_FILL(bp),
7170 		    avl_numnodes(t));
7171 	}
7172 
7173 	if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
7174 	    BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
7175 		return (0);
7176 
7177 	ddt_key_fill(&zdde_search.zdde_key, bp);
7178 
7179 	zdde = avl_find(t, &zdde_search, &where);
7180 
7181 	if (zdde == NULL) {
7182 		zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
7183 		zdde->zdde_key = zdde_search.zdde_key;
7184 		avl_insert(t, zdde, where);
7185 	}
7186 
7187 	zdde->zdde_ref_blocks += 1;
7188 	zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
7189 	zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
7190 	zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
7191 
7192 	return (0);
7193 }
7194 
7195 static void
7196 dump_simulated_ddt(spa_t *spa)
7197 {
7198 	avl_tree_t t;
7199 	void *cookie = NULL;
7200 	zdb_ddt_entry_t *zdde;
7201 	ddt_histogram_t ddh_total = {{{0}}};
7202 	ddt_stat_t dds_total = {0};
7203 
7204 	avl_create(&t, ddt_entry_compare,
7205 	    sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
7206 
7207 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7208 
7209 	(void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
7210 	    TRAVERSE_NO_DECRYPT, zdb_ddt_add_cb, &t);
7211 
7212 	spa_config_exit(spa, SCL_CONFIG, FTAG);
7213 
7214 	while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
7215 		ddt_stat_t dds;
7216 		uint64_t refcnt = zdde->zdde_ref_blocks;
7217 		ASSERT(refcnt != 0);
7218 
7219 		dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
7220 		dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
7221 		dds.dds_psize = zdde->zdde_ref_psize / refcnt;
7222 		dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
7223 
7224 		dds.dds_ref_blocks = zdde->zdde_ref_blocks;
7225 		dds.dds_ref_lsize = zdde->zdde_ref_lsize;
7226 		dds.dds_ref_psize = zdde->zdde_ref_psize;
7227 		dds.dds_ref_dsize = zdde->zdde_ref_dsize;
7228 
7229 		ddt_stat_add(&ddh_total.ddh_stat[highbit64(refcnt) - 1],
7230 		    &dds, 0);
7231 
7232 		umem_free(zdde, sizeof (*zdde));
7233 	}
7234 
7235 	avl_destroy(&t);
7236 
7237 	ddt_histogram_stat(&dds_total, &ddh_total);
7238 
7239 	(void) printf("Simulated DDT histogram:\n");
7240 
7241 	zpool_dump_ddt(&dds_total, &ddh_total);
7242 
7243 	dump_dedup_ratio(&dds_total);
7244 }
7245 
7246 static int
7247 verify_device_removal_feature_counts(spa_t *spa)
7248 {
7249 	uint64_t dr_feature_refcount = 0;
7250 	uint64_t oc_feature_refcount = 0;
7251 	uint64_t indirect_vdev_count = 0;
7252 	uint64_t precise_vdev_count = 0;
7253 	uint64_t obsolete_counts_object_count = 0;
7254 	uint64_t obsolete_sm_count = 0;
7255 	uint64_t obsolete_counts_count = 0;
7256 	uint64_t scip_count = 0;
7257 	uint64_t obsolete_bpobj_count = 0;
7258 	int ret = 0;
7259 
7260 	spa_condensing_indirect_phys_t *scip =
7261 	    &spa->spa_condensing_indirect_phys;
7262 	if (scip->scip_next_mapping_object != 0) {
7263 		vdev_t *vd = spa->spa_root_vdev->vdev_child[scip->scip_vdev];
7264 		ASSERT(scip->scip_prev_obsolete_sm_object != 0);
7265 		ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
7266 
7267 		(void) printf("Condensing indirect vdev %llu: new mapping "
7268 		    "object %llu, prev obsolete sm %llu\n",
7269 		    (u_longlong_t)scip->scip_vdev,
7270 		    (u_longlong_t)scip->scip_next_mapping_object,
7271 		    (u_longlong_t)scip->scip_prev_obsolete_sm_object);
7272 		if (scip->scip_prev_obsolete_sm_object != 0) {
7273 			space_map_t *prev_obsolete_sm = NULL;
7274 			VERIFY0(space_map_open(&prev_obsolete_sm,
7275 			    spa->spa_meta_objset,
7276 			    scip->scip_prev_obsolete_sm_object,
7277 			    0, vd->vdev_asize, 0));
7278 			dump_spacemap(spa->spa_meta_objset, prev_obsolete_sm);
7279 			(void) printf("\n");
7280 			space_map_close(prev_obsolete_sm);
7281 		}
7282 
7283 		scip_count += 2;
7284 	}
7285 
7286 	for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
7287 		vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
7288 		vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
7289 
7290 		if (vic->vic_mapping_object != 0) {
7291 			ASSERT(vd->vdev_ops == &vdev_indirect_ops ||
7292 			    vd->vdev_removing);
7293 			indirect_vdev_count++;
7294 
7295 			if (vd->vdev_indirect_mapping->vim_havecounts) {
7296 				obsolete_counts_count++;
7297 			}
7298 		}
7299 
7300 		boolean_t are_precise;
7301 		VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
7302 		if (are_precise) {
7303 			ASSERT(vic->vic_mapping_object != 0);
7304 			precise_vdev_count++;
7305 		}
7306 
7307 		uint64_t obsolete_sm_object;
7308 		VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
7309 		if (obsolete_sm_object != 0) {
7310 			ASSERT(vic->vic_mapping_object != 0);
7311 			obsolete_sm_count++;
7312 		}
7313 	}
7314 
7315 	(void) feature_get_refcount(spa,
7316 	    &spa_feature_table[SPA_FEATURE_DEVICE_REMOVAL],
7317 	    &dr_feature_refcount);
7318 	(void) feature_get_refcount(spa,
7319 	    &spa_feature_table[SPA_FEATURE_OBSOLETE_COUNTS],
7320 	    &oc_feature_refcount);
7321 
7322 	if (dr_feature_refcount != indirect_vdev_count) {
7323 		ret = 1;
7324 		(void) printf("Number of indirect vdevs (%llu) " \
7325 		    "does not match feature count (%llu)\n",
7326 		    (u_longlong_t)indirect_vdev_count,
7327 		    (u_longlong_t)dr_feature_refcount);
7328 	} else {
7329 		(void) printf("Verified device_removal feature refcount " \
7330 		    "of %llu is correct\n",
7331 		    (u_longlong_t)dr_feature_refcount);
7332 	}
7333 
7334 	if (zap_contains(spa_meta_objset(spa), DMU_POOL_DIRECTORY_OBJECT,
7335 	    DMU_POOL_OBSOLETE_BPOBJ) == 0) {
7336 		obsolete_bpobj_count++;
7337 	}
7338 
7339 
7340 	obsolete_counts_object_count = precise_vdev_count;
7341 	obsolete_counts_object_count += obsolete_sm_count;
7342 	obsolete_counts_object_count += obsolete_counts_count;
7343 	obsolete_counts_object_count += scip_count;
7344 	obsolete_counts_object_count += obsolete_bpobj_count;
7345 	obsolete_counts_object_count += remap_deadlist_count;
7346 
7347 	if (oc_feature_refcount != obsolete_counts_object_count) {
7348 		ret = 1;
7349 		(void) printf("Number of obsolete counts objects (%llu) " \
7350 		    "does not match feature count (%llu)\n",
7351 		    (u_longlong_t)obsolete_counts_object_count,
7352 		    (u_longlong_t)oc_feature_refcount);
7353 		(void) printf("pv:%llu os:%llu oc:%llu sc:%llu "
7354 		    "ob:%llu rd:%llu\n",
7355 		    (u_longlong_t)precise_vdev_count,
7356 		    (u_longlong_t)obsolete_sm_count,
7357 		    (u_longlong_t)obsolete_counts_count,
7358 		    (u_longlong_t)scip_count,
7359 		    (u_longlong_t)obsolete_bpobj_count,
7360 		    (u_longlong_t)remap_deadlist_count);
7361 	} else {
7362 		(void) printf("Verified indirect_refcount feature refcount " \
7363 		    "of %llu is correct\n",
7364 		    (u_longlong_t)oc_feature_refcount);
7365 	}
7366 	return (ret);
7367 }
7368 
7369 static void
7370 zdb_set_skip_mmp(char *target)
7371 {
7372 	spa_t *spa;
7373 
7374 	/*
7375 	 * Disable the activity check to allow examination of
7376 	 * active pools.
7377 	 */
7378 	mutex_enter(&spa_namespace_lock);
7379 	if ((spa = spa_lookup(target)) != NULL) {
7380 		spa->spa_import_flags |= ZFS_IMPORT_SKIP_MMP;
7381 	}
7382 	mutex_exit(&spa_namespace_lock);
7383 }
7384 
7385 #define	BOGUS_SUFFIX "_CHECKPOINTED_UNIVERSE"
7386 /*
7387  * Import the checkpointed state of the pool specified by the target
7388  * parameter as readonly. The function also accepts a pool config
7389  * as an optional parameter, else it attempts to infer the config by
7390  * the name of the target pool.
7391  *
7392  * Note that the checkpointed state's pool name will be the name of
7393  * the original pool with the above suffix appended to it. In addition,
7394  * if the target is not a pool name (e.g. a path to a dataset) then
7395  * the new_path parameter is populated with the updated path to
7396  * reflect the fact that we are looking into the checkpointed state.
7397  *
7398  * The function returns a newly-allocated copy of the name of the
7399  * pool containing the checkpointed state. When this copy is no
7400  * longer needed it should be freed with free(3C). Same thing
7401  * applies to the new_path parameter if allocated.
7402  */
7403 static char *
7404 import_checkpointed_state(char *target, nvlist_t *cfg, char **new_path)
7405 {
7406 	int error = 0;
7407 	char *poolname, *bogus_name = NULL;
7408 	boolean_t freecfg = B_FALSE;
7409 
7410 	/* If the target is not a pool, the extract the pool name */
7411 	char *path_start = strchr(target, '/');
7412 	if (path_start != NULL) {
7413 		size_t poolname_len = path_start - target;
7414 		poolname = strndup(target, poolname_len);
7415 	} else {
7416 		poolname = target;
7417 	}
7418 
7419 	if (cfg == NULL) {
7420 		zdb_set_skip_mmp(poolname);
7421 		error = spa_get_stats(poolname, &cfg, NULL, 0);
7422 		if (error != 0) {
7423 			fatal("Tried to read config of pool \"%s\" but "
7424 			    "spa_get_stats() failed with error %d\n",
7425 			    poolname, error);
7426 		}
7427 		freecfg = B_TRUE;
7428 	}
7429 
7430 	if (asprintf(&bogus_name, "%s%s", poolname, BOGUS_SUFFIX) == -1) {
7431 		if (target != poolname)
7432 			free(poolname);
7433 		return (NULL);
7434 	}
7435 	fnvlist_add_string(cfg, ZPOOL_CONFIG_POOL_NAME, bogus_name);
7436 
7437 	error = spa_import(bogus_name, cfg, NULL,
7438 	    ZFS_IMPORT_MISSING_LOG | ZFS_IMPORT_CHECKPOINT |
7439 	    ZFS_IMPORT_SKIP_MMP);
7440 	if (freecfg)
7441 		nvlist_free(cfg);
7442 	if (error != 0) {
7443 		fatal("Tried to import pool \"%s\" but spa_import() failed "
7444 		    "with error %d\n", bogus_name, error);
7445 	}
7446 
7447 	if (new_path != NULL && path_start != NULL) {
7448 		if (asprintf(new_path, "%s%s", bogus_name, path_start) == -1) {
7449 			free(bogus_name);
7450 			if (path_start != NULL)
7451 				free(poolname);
7452 			return (NULL);
7453 		}
7454 	}
7455 
7456 	if (target != poolname)
7457 		free(poolname);
7458 
7459 	return (bogus_name);
7460 }
7461 
7462 typedef struct verify_checkpoint_sm_entry_cb_arg {
7463 	vdev_t *vcsec_vd;
7464 
7465 	/* the following fields are only used for printing progress */
7466 	uint64_t vcsec_entryid;
7467 	uint64_t vcsec_num_entries;
7468 } verify_checkpoint_sm_entry_cb_arg_t;
7469 
7470 #define	ENTRIES_PER_PROGRESS_UPDATE 10000
7471 
7472 static int
7473 verify_checkpoint_sm_entry_cb(space_map_entry_t *sme, void *arg)
7474 {
7475 	verify_checkpoint_sm_entry_cb_arg_t *vcsec = arg;
7476 	vdev_t *vd = vcsec->vcsec_vd;
7477 	metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
7478 	uint64_t end = sme->sme_offset + sme->sme_run;
7479 
7480 	ASSERT(sme->sme_type == SM_FREE);
7481 
7482 	if ((vcsec->vcsec_entryid % ENTRIES_PER_PROGRESS_UPDATE) == 0) {
7483 		(void) fprintf(stderr,
7484 		    "\rverifying vdev %llu, space map entry %llu of %llu ...",
7485 		    (longlong_t)vd->vdev_id,
7486 		    (longlong_t)vcsec->vcsec_entryid,
7487 		    (longlong_t)vcsec->vcsec_num_entries);
7488 	}
7489 	vcsec->vcsec_entryid++;
7490 
7491 	/*
7492 	 * See comment in checkpoint_sm_exclude_entry_cb()
7493 	 */
7494 	VERIFY3U(sme->sme_offset, >=, ms->ms_start);
7495 	VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
7496 
7497 	/*
7498 	 * The entries in the vdev_checkpoint_sm should be marked as
7499 	 * allocated in the checkpointed state of the pool, therefore
7500 	 * their respective ms_allocateable trees should not contain them.
7501 	 */
7502 	mutex_enter(&ms->ms_lock);
7503 	range_tree_verify_not_present(ms->ms_allocatable,
7504 	    sme->sme_offset, sme->sme_run);
7505 	mutex_exit(&ms->ms_lock);
7506 
7507 	return (0);
7508 }
7509 
7510 /*
7511  * Verify that all segments in the vdev_checkpoint_sm are allocated
7512  * according to the checkpoint's ms_sm (i.e. are not in the checkpoint's
7513  * ms_allocatable).
7514  *
7515  * Do so by comparing the checkpoint space maps (vdev_checkpoint_sm) of
7516  * each vdev in the current state of the pool to the metaslab space maps
7517  * (ms_sm) of the checkpointed state of the pool.
7518  *
7519  * Note that the function changes the state of the ms_allocatable
7520  * trees of the current spa_t. The entries of these ms_allocatable
7521  * trees are cleared out and then repopulated from with the free
7522  * entries of their respective ms_sm space maps.
7523  */
7524 static void
7525 verify_checkpoint_vdev_spacemaps(spa_t *checkpoint, spa_t *current)
7526 {
7527 	vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
7528 	vdev_t *current_rvd = current->spa_root_vdev;
7529 
7530 	load_concrete_ms_allocatable_trees(checkpoint, SM_FREE);
7531 
7532 	for (uint64_t c = 0; c < ckpoint_rvd->vdev_children; c++) {
7533 		vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[c];
7534 		vdev_t *current_vd = current_rvd->vdev_child[c];
7535 
7536 		space_map_t *checkpoint_sm = NULL;
7537 		uint64_t checkpoint_sm_obj;
7538 
7539 		if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
7540 			/*
7541 			 * Since we don't allow device removal in a pool
7542 			 * that has a checkpoint, we expect that all removed
7543 			 * vdevs were removed from the pool before the
7544 			 * checkpoint.
7545 			 */
7546 			ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
7547 			continue;
7548 		}
7549 
7550 		/*
7551 		 * If the checkpoint space map doesn't exist, then nothing
7552 		 * here is checkpointed so there's nothing to verify.
7553 		 */
7554 		if (current_vd->vdev_top_zap == 0 ||
7555 		    zap_contains(spa_meta_objset(current),
7556 		    current_vd->vdev_top_zap,
7557 		    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
7558 			continue;
7559 
7560 		VERIFY0(zap_lookup(spa_meta_objset(current),
7561 		    current_vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
7562 		    sizeof (uint64_t), 1, &checkpoint_sm_obj));
7563 
7564 		VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(current),
7565 		    checkpoint_sm_obj, 0, current_vd->vdev_asize,
7566 		    current_vd->vdev_ashift));
7567 
7568 		verify_checkpoint_sm_entry_cb_arg_t vcsec;
7569 		vcsec.vcsec_vd = ckpoint_vd;
7570 		vcsec.vcsec_entryid = 0;
7571 		vcsec.vcsec_num_entries =
7572 		    space_map_length(checkpoint_sm) / sizeof (uint64_t);
7573 		VERIFY0(space_map_iterate(checkpoint_sm,
7574 		    space_map_length(checkpoint_sm),
7575 		    verify_checkpoint_sm_entry_cb, &vcsec));
7576 		if (dump_opt['m'] > 3)
7577 			dump_spacemap(current->spa_meta_objset, checkpoint_sm);
7578 		space_map_close(checkpoint_sm);
7579 	}
7580 
7581 	/*
7582 	 * If we've added vdevs since we took the checkpoint, ensure
7583 	 * that their checkpoint space maps are empty.
7584 	 */
7585 	if (ckpoint_rvd->vdev_children < current_rvd->vdev_children) {
7586 		for (uint64_t c = ckpoint_rvd->vdev_children;
7587 		    c < current_rvd->vdev_children; c++) {
7588 			vdev_t *current_vd = current_rvd->vdev_child[c];
7589 			VERIFY3P(current_vd->vdev_checkpoint_sm, ==, NULL);
7590 		}
7591 	}
7592 
7593 	/* for cleaner progress output */
7594 	(void) fprintf(stderr, "\n");
7595 }
7596 
7597 /*
7598  * Verifies that all space that's allocated in the checkpoint is
7599  * still allocated in the current version, by checking that everything
7600  * in checkpoint's ms_allocatable (which is actually allocated, not
7601  * allocatable/free) is not present in current's ms_allocatable.
7602  *
7603  * Note that the function changes the state of the ms_allocatable
7604  * trees of both spas when called. The entries of all ms_allocatable
7605  * trees are cleared out and then repopulated from their respective
7606  * ms_sm space maps. In the checkpointed state we load the allocated
7607  * entries, and in the current state we load the free entries.
7608  */
7609 static void
7610 verify_checkpoint_ms_spacemaps(spa_t *checkpoint, spa_t *current)
7611 {
7612 	vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
7613 	vdev_t *current_rvd = current->spa_root_vdev;
7614 
7615 	load_concrete_ms_allocatable_trees(checkpoint, SM_ALLOC);
7616 	load_concrete_ms_allocatable_trees(current, SM_FREE);
7617 
7618 	for (uint64_t i = 0; i < ckpoint_rvd->vdev_children; i++) {
7619 		vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[i];
7620 		vdev_t *current_vd = current_rvd->vdev_child[i];
7621 
7622 		if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
7623 			/*
7624 			 * See comment in verify_checkpoint_vdev_spacemaps()
7625 			 */
7626 			ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
7627 			continue;
7628 		}
7629 
7630 		for (uint64_t m = 0; m < ckpoint_vd->vdev_ms_count; m++) {
7631 			metaslab_t *ckpoint_msp = ckpoint_vd->vdev_ms[m];
7632 			metaslab_t *current_msp = current_vd->vdev_ms[m];
7633 
7634 			(void) fprintf(stderr,
7635 			    "\rverifying vdev %llu of %llu, "
7636 			    "metaslab %llu of %llu ...",
7637 			    (longlong_t)current_vd->vdev_id,
7638 			    (longlong_t)current_rvd->vdev_children,
7639 			    (longlong_t)current_vd->vdev_ms[m]->ms_id,
7640 			    (longlong_t)current_vd->vdev_ms_count);
7641 
7642 			/*
7643 			 * We walk through the ms_allocatable trees that
7644 			 * are loaded with the allocated blocks from the
7645 			 * ms_sm spacemaps of the checkpoint. For each
7646 			 * one of these ranges we ensure that none of them
7647 			 * exists in the ms_allocatable trees of the
7648 			 * current state which are loaded with the ranges
7649 			 * that are currently free.
7650 			 *
7651 			 * This way we ensure that none of the blocks that
7652 			 * are part of the checkpoint were freed by mistake.
7653 			 */
7654 			range_tree_walk(ckpoint_msp->ms_allocatable,
7655 			    (range_tree_func_t *)range_tree_verify_not_present,
7656 			    current_msp->ms_allocatable);
7657 		}
7658 	}
7659 
7660 	/* for cleaner progress output */
7661 	(void) fprintf(stderr, "\n");
7662 }
7663 
7664 static void
7665 verify_checkpoint_blocks(spa_t *spa)
7666 {
7667 	ASSERT(!dump_opt['L']);
7668 
7669 	spa_t *checkpoint_spa;
7670 	char *checkpoint_pool;
7671 	int error = 0;
7672 
7673 	/*
7674 	 * We import the checkpointed state of the pool (under a different
7675 	 * name) so we can do verification on it against the current state
7676 	 * of the pool.
7677 	 */
7678 	checkpoint_pool = import_checkpointed_state(spa->spa_name, NULL,
7679 	    NULL);
7680 	ASSERT(strcmp(spa->spa_name, checkpoint_pool) != 0);
7681 
7682 	error = spa_open(checkpoint_pool, &checkpoint_spa, FTAG);
7683 	if (error != 0) {
7684 		fatal("Tried to open pool \"%s\" but spa_open() failed with "
7685 		    "error %d\n", checkpoint_pool, error);
7686 	}
7687 
7688 	/*
7689 	 * Ensure that ranges in the checkpoint space maps of each vdev
7690 	 * are allocated according to the checkpointed state's metaslab
7691 	 * space maps.
7692 	 */
7693 	verify_checkpoint_vdev_spacemaps(checkpoint_spa, spa);
7694 
7695 	/*
7696 	 * Ensure that allocated ranges in the checkpoint's metaslab
7697 	 * space maps remain allocated in the metaslab space maps of
7698 	 * the current state.
7699 	 */
7700 	verify_checkpoint_ms_spacemaps(checkpoint_spa, spa);
7701 
7702 	/*
7703 	 * Once we are done, we get rid of the checkpointed state.
7704 	 */
7705 	spa_close(checkpoint_spa, FTAG);
7706 	free(checkpoint_pool);
7707 }
7708 
7709 static void
7710 dump_leftover_checkpoint_blocks(spa_t *spa)
7711 {
7712 	vdev_t *rvd = spa->spa_root_vdev;
7713 
7714 	for (uint64_t i = 0; i < rvd->vdev_children; i++) {
7715 		vdev_t *vd = rvd->vdev_child[i];
7716 
7717 		space_map_t *checkpoint_sm = NULL;
7718 		uint64_t checkpoint_sm_obj;
7719 
7720 		if (vd->vdev_top_zap == 0)
7721 			continue;
7722 
7723 		if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
7724 		    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
7725 			continue;
7726 
7727 		VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
7728 		    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
7729 		    sizeof (uint64_t), 1, &checkpoint_sm_obj));
7730 
7731 		VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
7732 		    checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
7733 		dump_spacemap(spa->spa_meta_objset, checkpoint_sm);
7734 		space_map_close(checkpoint_sm);
7735 	}
7736 }
7737 
7738 static int
7739 verify_checkpoint(spa_t *spa)
7740 {
7741 	uberblock_t checkpoint;
7742 	int error;
7743 
7744 	if (!spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT))
7745 		return (0);
7746 
7747 	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7748 	    DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
7749 	    sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
7750 
7751 	if (error == ENOENT && !dump_opt['L']) {
7752 		/*
7753 		 * If the feature is active but the uberblock is missing
7754 		 * then we must be in the middle of discarding the
7755 		 * checkpoint.
7756 		 */
7757 		(void) printf("\nPartially discarded checkpoint "
7758 		    "state found:\n");
7759 		if (dump_opt['m'] > 3)
7760 			dump_leftover_checkpoint_blocks(spa);
7761 		return (0);
7762 	} else if (error != 0) {
7763 		(void) printf("lookup error %d when looking for "
7764 		    "checkpointed uberblock in MOS\n", error);
7765 		return (error);
7766 	}
7767 	dump_uberblock(&checkpoint, "\nCheckpointed uberblock found:\n", "\n");
7768 
7769 	if (checkpoint.ub_checkpoint_txg == 0) {
7770 		(void) printf("\nub_checkpoint_txg not set in checkpointed "
7771 		    "uberblock\n");
7772 		error = 3;
7773 	}
7774 
7775 	if (error == 0 && !dump_opt['L'])
7776 		verify_checkpoint_blocks(spa);
7777 
7778 	return (error);
7779 }
7780 
7781 static void
7782 mos_leaks_cb(void *arg, uint64_t start, uint64_t size)
7783 {
7784 	(void) arg;
7785 	for (uint64_t i = start; i < size; i++) {
7786 		(void) printf("MOS object %llu referenced but not allocated\n",
7787 		    (u_longlong_t)i);
7788 	}
7789 }
7790 
7791 static void
7792 mos_obj_refd(uint64_t obj)
7793 {
7794 	if (obj != 0 && mos_refd_objs != NULL)
7795 		range_tree_add(mos_refd_objs, obj, 1);
7796 }
7797 
7798 /*
7799  * Call on a MOS object that may already have been referenced.
7800  */
7801 static void
7802 mos_obj_refd_multiple(uint64_t obj)
7803 {
7804 	if (obj != 0 && mos_refd_objs != NULL &&
7805 	    !range_tree_contains(mos_refd_objs, obj, 1))
7806 		range_tree_add(mos_refd_objs, obj, 1);
7807 }
7808 
7809 static void
7810 mos_leak_vdev_top_zap(vdev_t *vd)
7811 {
7812 	uint64_t ms_flush_data_obj;
7813 	int error = zap_lookup(spa_meta_objset(vd->vdev_spa),
7814 	    vd->vdev_top_zap, VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS,
7815 	    sizeof (ms_flush_data_obj), 1, &ms_flush_data_obj);
7816 	if (error == ENOENT)
7817 		return;
7818 	ASSERT0(error);
7819 
7820 	mos_obj_refd(ms_flush_data_obj);
7821 }
7822 
7823 static void
7824 mos_leak_vdev(vdev_t *vd)
7825 {
7826 	mos_obj_refd(vd->vdev_dtl_object);
7827 	mos_obj_refd(vd->vdev_ms_array);
7828 	mos_obj_refd(vd->vdev_indirect_config.vic_births_object);
7829 	mos_obj_refd(vd->vdev_indirect_config.vic_mapping_object);
7830 	mos_obj_refd(vd->vdev_leaf_zap);
7831 	if (vd->vdev_checkpoint_sm != NULL)
7832 		mos_obj_refd(vd->vdev_checkpoint_sm->sm_object);
7833 	if (vd->vdev_indirect_mapping != NULL) {
7834 		mos_obj_refd(vd->vdev_indirect_mapping->
7835 		    vim_phys->vimp_counts_object);
7836 	}
7837 	if (vd->vdev_obsolete_sm != NULL)
7838 		mos_obj_refd(vd->vdev_obsolete_sm->sm_object);
7839 
7840 	for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
7841 		metaslab_t *ms = vd->vdev_ms[m];
7842 		mos_obj_refd(space_map_object(ms->ms_sm));
7843 	}
7844 
7845 	if (vd->vdev_root_zap != 0)
7846 		mos_obj_refd(vd->vdev_root_zap);
7847 
7848 	if (vd->vdev_top_zap != 0) {
7849 		mos_obj_refd(vd->vdev_top_zap);
7850 		mos_leak_vdev_top_zap(vd);
7851 	}
7852 
7853 	for (uint64_t c = 0; c < vd->vdev_children; c++) {
7854 		mos_leak_vdev(vd->vdev_child[c]);
7855 	}
7856 }
7857 
7858 static void
7859 mos_leak_log_spacemaps(spa_t *spa)
7860 {
7861 	uint64_t spacemap_zap;
7862 	int error = zap_lookup(spa_meta_objset(spa),
7863 	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_LOG_SPACEMAP_ZAP,
7864 	    sizeof (spacemap_zap), 1, &spacemap_zap);
7865 	if (error == ENOENT)
7866 		return;
7867 	ASSERT0(error);
7868 
7869 	mos_obj_refd(spacemap_zap);
7870 	for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
7871 	    sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls))
7872 		mos_obj_refd(sls->sls_sm_obj);
7873 }
7874 
7875 static void
7876 errorlog_count_refd(objset_t *mos, uint64_t errlog)
7877 {
7878 	zap_cursor_t zc;
7879 	zap_attribute_t za;
7880 	for (zap_cursor_init(&zc, mos, errlog);
7881 	    zap_cursor_retrieve(&zc, &za) == 0;
7882 	    zap_cursor_advance(&zc)) {
7883 		mos_obj_refd(za.za_first_integer);
7884 	}
7885 	zap_cursor_fini(&zc);
7886 }
7887 
7888 static int
7889 dump_mos_leaks(spa_t *spa)
7890 {
7891 	int rv = 0;
7892 	objset_t *mos = spa->spa_meta_objset;
7893 	dsl_pool_t *dp = spa->spa_dsl_pool;
7894 
7895 	/* Visit and mark all referenced objects in the MOS */
7896 
7897 	mos_obj_refd(DMU_POOL_DIRECTORY_OBJECT);
7898 	mos_obj_refd(spa->spa_pool_props_object);
7899 	mos_obj_refd(spa->spa_config_object);
7900 	mos_obj_refd(spa->spa_ddt_stat_object);
7901 	mos_obj_refd(spa->spa_feat_desc_obj);
7902 	mos_obj_refd(spa->spa_feat_enabled_txg_obj);
7903 	mos_obj_refd(spa->spa_feat_for_read_obj);
7904 	mos_obj_refd(spa->spa_feat_for_write_obj);
7905 	mos_obj_refd(spa->spa_history);
7906 	mos_obj_refd(spa->spa_errlog_last);
7907 	mos_obj_refd(spa->spa_errlog_scrub);
7908 
7909 	if (spa_feature_is_enabled(spa, SPA_FEATURE_HEAD_ERRLOG)) {
7910 		errorlog_count_refd(mos, spa->spa_errlog_last);
7911 		errorlog_count_refd(mos, spa->spa_errlog_scrub);
7912 	}
7913 
7914 	mos_obj_refd(spa->spa_all_vdev_zaps);
7915 	mos_obj_refd(spa->spa_dsl_pool->dp_bptree_obj);
7916 	mos_obj_refd(spa->spa_dsl_pool->dp_tmp_userrefs_obj);
7917 	mos_obj_refd(spa->spa_dsl_pool->dp_scan->scn_phys.scn_queue_obj);
7918 	bpobj_count_refd(&spa->spa_deferred_bpobj);
7919 	mos_obj_refd(dp->dp_empty_bpobj);
7920 	bpobj_count_refd(&dp->dp_obsolete_bpobj);
7921 	bpobj_count_refd(&dp->dp_free_bpobj);
7922 	mos_obj_refd(spa->spa_l2cache.sav_object);
7923 	mos_obj_refd(spa->spa_spares.sav_object);
7924 
7925 	if (spa->spa_syncing_log_sm != NULL)
7926 		mos_obj_refd(spa->spa_syncing_log_sm->sm_object);
7927 	mos_leak_log_spacemaps(spa);
7928 
7929 	mos_obj_refd(spa->spa_condensing_indirect_phys.
7930 	    scip_next_mapping_object);
7931 	mos_obj_refd(spa->spa_condensing_indirect_phys.
7932 	    scip_prev_obsolete_sm_object);
7933 	if (spa->spa_condensing_indirect_phys.scip_next_mapping_object != 0) {
7934 		vdev_indirect_mapping_t *vim =
7935 		    vdev_indirect_mapping_open(mos,
7936 		    spa->spa_condensing_indirect_phys.scip_next_mapping_object);
7937 		mos_obj_refd(vim->vim_phys->vimp_counts_object);
7938 		vdev_indirect_mapping_close(vim);
7939 	}
7940 	deleted_livelists_dump_mos(spa);
7941 
7942 	if (dp->dp_origin_snap != NULL) {
7943 		dsl_dataset_t *ds;
7944 
7945 		dsl_pool_config_enter(dp, FTAG);
7946 		VERIFY0(dsl_dataset_hold_obj(dp,
7947 		    dsl_dataset_phys(dp->dp_origin_snap)->ds_next_snap_obj,
7948 		    FTAG, &ds));
7949 		count_ds_mos_objects(ds);
7950 		dump_blkptr_list(&ds->ds_deadlist, "Deadlist");
7951 		dsl_dataset_rele(ds, FTAG);
7952 		dsl_pool_config_exit(dp, FTAG);
7953 
7954 		count_ds_mos_objects(dp->dp_origin_snap);
7955 		dump_blkptr_list(&dp->dp_origin_snap->ds_deadlist, "Deadlist");
7956 	}
7957 	count_dir_mos_objects(dp->dp_mos_dir);
7958 	if (dp->dp_free_dir != NULL)
7959 		count_dir_mos_objects(dp->dp_free_dir);
7960 	if (dp->dp_leak_dir != NULL)
7961 		count_dir_mos_objects(dp->dp_leak_dir);
7962 
7963 	mos_leak_vdev(spa->spa_root_vdev);
7964 
7965 	for (uint64_t class = 0; class < DDT_CLASSES; class++) {
7966 		for (uint64_t type = 0; type < DDT_TYPES; type++) {
7967 			for (uint64_t cksum = 0;
7968 			    cksum < ZIO_CHECKSUM_FUNCTIONS; cksum++) {
7969 				ddt_t *ddt = spa->spa_ddt[cksum];
7970 				mos_obj_refd(ddt->ddt_object[type][class]);
7971 			}
7972 		}
7973 	}
7974 
7975 	/*
7976 	 * Visit all allocated objects and make sure they are referenced.
7977 	 */
7978 	uint64_t object = 0;
7979 	while (dmu_object_next(mos, &object, B_FALSE, 0) == 0) {
7980 		if (range_tree_contains(mos_refd_objs, object, 1)) {
7981 			range_tree_remove(mos_refd_objs, object, 1);
7982 		} else {
7983 			dmu_object_info_t doi;
7984 			const char *name;
7985 			VERIFY0(dmu_object_info(mos, object, &doi));
7986 			if (doi.doi_type & DMU_OT_NEWTYPE) {
7987 				dmu_object_byteswap_t bswap =
7988 				    DMU_OT_BYTESWAP(doi.doi_type);
7989 				name = dmu_ot_byteswap[bswap].ob_name;
7990 			} else {
7991 				name = dmu_ot[doi.doi_type].ot_name;
7992 			}
7993 
7994 			(void) printf("MOS object %llu (%s) leaked\n",
7995 			    (u_longlong_t)object, name);
7996 			rv = 2;
7997 		}
7998 	}
7999 	(void) range_tree_walk(mos_refd_objs, mos_leaks_cb, NULL);
8000 	if (!range_tree_is_empty(mos_refd_objs))
8001 		rv = 2;
8002 	range_tree_vacate(mos_refd_objs, NULL, NULL);
8003 	range_tree_destroy(mos_refd_objs);
8004 	return (rv);
8005 }
8006 
8007 typedef struct log_sm_obsolete_stats_arg {
8008 	uint64_t lsos_current_txg;
8009 
8010 	uint64_t lsos_total_entries;
8011 	uint64_t lsos_valid_entries;
8012 
8013 	uint64_t lsos_sm_entries;
8014 	uint64_t lsos_valid_sm_entries;
8015 } log_sm_obsolete_stats_arg_t;
8016 
8017 static int
8018 log_spacemap_obsolete_stats_cb(spa_t *spa, space_map_entry_t *sme,
8019     uint64_t txg, void *arg)
8020 {
8021 	log_sm_obsolete_stats_arg_t *lsos = arg;
8022 
8023 	uint64_t offset = sme->sme_offset;
8024 	uint64_t vdev_id = sme->sme_vdev;
8025 
8026 	if (lsos->lsos_current_txg == 0) {
8027 		/* this is the first log */
8028 		lsos->lsos_current_txg = txg;
8029 	} else if (lsos->lsos_current_txg < txg) {
8030 		/* we just changed log - print stats and reset */
8031 		(void) printf("%-8llu valid entries out of %-8llu - txg %llu\n",
8032 		    (u_longlong_t)lsos->lsos_valid_sm_entries,
8033 		    (u_longlong_t)lsos->lsos_sm_entries,
8034 		    (u_longlong_t)lsos->lsos_current_txg);
8035 		lsos->lsos_valid_sm_entries = 0;
8036 		lsos->lsos_sm_entries = 0;
8037 		lsos->lsos_current_txg = txg;
8038 	}
8039 	ASSERT3U(lsos->lsos_current_txg, ==, txg);
8040 
8041 	lsos->lsos_sm_entries++;
8042 	lsos->lsos_total_entries++;
8043 
8044 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
8045 	if (!vdev_is_concrete(vd))
8046 		return (0);
8047 
8048 	metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
8049 	ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
8050 
8051 	if (txg < metaslab_unflushed_txg(ms))
8052 		return (0);
8053 	lsos->lsos_valid_sm_entries++;
8054 	lsos->lsos_valid_entries++;
8055 	return (0);
8056 }
8057 
8058 static void
8059 dump_log_spacemap_obsolete_stats(spa_t *spa)
8060 {
8061 	if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
8062 		return;
8063 
8064 	log_sm_obsolete_stats_arg_t lsos = {0};
8065 
8066 	(void) printf("Log Space Map Obsolete Entry Statistics:\n");
8067 
8068 	iterate_through_spacemap_logs(spa,
8069 	    log_spacemap_obsolete_stats_cb, &lsos);
8070 
8071 	/* print stats for latest log */
8072 	(void) printf("%-8llu valid entries out of %-8llu - txg %llu\n",
8073 	    (u_longlong_t)lsos.lsos_valid_sm_entries,
8074 	    (u_longlong_t)lsos.lsos_sm_entries,
8075 	    (u_longlong_t)lsos.lsos_current_txg);
8076 
8077 	(void) printf("%-8llu valid entries out of %-8llu - total\n\n",
8078 	    (u_longlong_t)lsos.lsos_valid_entries,
8079 	    (u_longlong_t)lsos.lsos_total_entries);
8080 }
8081 
8082 static void
8083 dump_zpool(spa_t *spa)
8084 {
8085 	dsl_pool_t *dp = spa_get_dsl(spa);
8086 	int rc = 0;
8087 
8088 	if (dump_opt['y']) {
8089 		livelist_metaslab_validate(spa);
8090 	}
8091 
8092 	if (dump_opt['S']) {
8093 		dump_simulated_ddt(spa);
8094 		return;
8095 	}
8096 
8097 	if (!dump_opt['e'] && dump_opt['C'] > 1) {
8098 		(void) printf("\nCached configuration:\n");
8099 		dump_nvlist(spa->spa_config, 8);
8100 	}
8101 
8102 	if (dump_opt['C'])
8103 		dump_config(spa);
8104 
8105 	if (dump_opt['u'])
8106 		dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
8107 
8108 	if (dump_opt['D'])
8109 		dump_all_ddts(spa);
8110 
8111 	if (dump_opt['d'] > 2 || dump_opt['m'])
8112 		dump_metaslabs(spa);
8113 	if (dump_opt['M'])
8114 		dump_metaslab_groups(spa, dump_opt['M'] > 1);
8115 	if (dump_opt['d'] > 2 || dump_opt['m']) {
8116 		dump_log_spacemaps(spa);
8117 		dump_log_spacemap_obsolete_stats(spa);
8118 	}
8119 
8120 	if (dump_opt['d'] || dump_opt['i']) {
8121 		spa_feature_t f;
8122 		mos_refd_objs = range_tree_create(NULL, RANGE_SEG64, NULL, 0,
8123 		    0);
8124 		dump_objset(dp->dp_meta_objset);
8125 
8126 		if (dump_opt['d'] >= 3) {
8127 			dsl_pool_t *dp = spa->spa_dsl_pool;
8128 			dump_full_bpobj(&spa->spa_deferred_bpobj,
8129 			    "Deferred frees", 0);
8130 			if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
8131 				dump_full_bpobj(&dp->dp_free_bpobj,
8132 				    "Pool snapshot frees", 0);
8133 			}
8134 			if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
8135 				ASSERT(spa_feature_is_enabled(spa,
8136 				    SPA_FEATURE_DEVICE_REMOVAL));
8137 				dump_full_bpobj(&dp->dp_obsolete_bpobj,
8138 				    "Pool obsolete blocks", 0);
8139 			}
8140 
8141 			if (spa_feature_is_active(spa,
8142 			    SPA_FEATURE_ASYNC_DESTROY)) {
8143 				dump_bptree(spa->spa_meta_objset,
8144 				    dp->dp_bptree_obj,
8145 				    "Pool dataset frees");
8146 			}
8147 			dump_dtl(spa->spa_root_vdev, 0);
8148 		}
8149 
8150 		for (spa_feature_t f = 0; f < SPA_FEATURES; f++)
8151 			global_feature_count[f] = UINT64_MAX;
8152 		global_feature_count[SPA_FEATURE_REDACTION_BOOKMARKS] = 0;
8153 		global_feature_count[SPA_FEATURE_REDACTION_LIST_SPILL] = 0;
8154 		global_feature_count[SPA_FEATURE_BOOKMARK_WRITTEN] = 0;
8155 		global_feature_count[SPA_FEATURE_LIVELIST] = 0;
8156 
8157 		(void) dmu_objset_find(spa_name(spa), dump_one_objset,
8158 		    NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
8159 
8160 		if (rc == 0 && !dump_opt['L'])
8161 			rc = dump_mos_leaks(spa);
8162 
8163 		for (f = 0; f < SPA_FEATURES; f++) {
8164 			uint64_t refcount;
8165 
8166 			uint64_t *arr;
8167 			if (!(spa_feature_table[f].fi_flags &
8168 			    ZFEATURE_FLAG_PER_DATASET)) {
8169 				if (global_feature_count[f] == UINT64_MAX)
8170 					continue;
8171 				if (!spa_feature_is_enabled(spa, f)) {
8172 					ASSERT0(global_feature_count[f]);
8173 					continue;
8174 				}
8175 				arr = global_feature_count;
8176 			} else {
8177 				if (!spa_feature_is_enabled(spa, f)) {
8178 					ASSERT0(dataset_feature_count[f]);
8179 					continue;
8180 				}
8181 				arr = dataset_feature_count;
8182 			}
8183 			if (feature_get_refcount(spa, &spa_feature_table[f],
8184 			    &refcount) == ENOTSUP)
8185 				continue;
8186 			if (arr[f] != refcount) {
8187 				(void) printf("%s feature refcount mismatch: "
8188 				    "%lld consumers != %lld refcount\n",
8189 				    spa_feature_table[f].fi_uname,
8190 				    (longlong_t)arr[f], (longlong_t)refcount);
8191 				rc = 2;
8192 			} else {
8193 				(void) printf("Verified %s feature refcount "
8194 				    "of %llu is correct\n",
8195 				    spa_feature_table[f].fi_uname,
8196 				    (longlong_t)refcount);
8197 			}
8198 		}
8199 
8200 		if (rc == 0)
8201 			rc = verify_device_removal_feature_counts(spa);
8202 	}
8203 
8204 	if (rc == 0 && (dump_opt['b'] || dump_opt['c']))
8205 		rc = dump_block_stats(spa);
8206 
8207 	if (rc == 0)
8208 		rc = verify_spacemap_refcounts(spa);
8209 
8210 	if (dump_opt['s'])
8211 		show_pool_stats(spa);
8212 
8213 	if (dump_opt['h'])
8214 		dump_history(spa);
8215 
8216 	if (rc == 0)
8217 		rc = verify_checkpoint(spa);
8218 
8219 	if (rc != 0) {
8220 		dump_debug_buffer();
8221 		exit(rc);
8222 	}
8223 }
8224 
8225 #define	ZDB_FLAG_CHECKSUM	0x0001
8226 #define	ZDB_FLAG_DECOMPRESS	0x0002
8227 #define	ZDB_FLAG_BSWAP		0x0004
8228 #define	ZDB_FLAG_GBH		0x0008
8229 #define	ZDB_FLAG_INDIRECT	0x0010
8230 #define	ZDB_FLAG_RAW		0x0020
8231 #define	ZDB_FLAG_PRINT_BLKPTR	0x0040
8232 #define	ZDB_FLAG_VERBOSE	0x0080
8233 
8234 static int flagbits[256];
8235 static char flagbitstr[16];
8236 
8237 static void
8238 zdb_print_blkptr(const blkptr_t *bp, int flags)
8239 {
8240 	char blkbuf[BP_SPRINTF_LEN];
8241 
8242 	if (flags & ZDB_FLAG_BSWAP)
8243 		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
8244 
8245 	snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
8246 	(void) printf("%s\n", blkbuf);
8247 }
8248 
8249 static void
8250 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
8251 {
8252 	int i;
8253 
8254 	for (i = 0; i < nbps; i++)
8255 		zdb_print_blkptr(&bp[i], flags);
8256 }
8257 
8258 static void
8259 zdb_dump_gbh(void *buf, int flags)
8260 {
8261 	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
8262 }
8263 
8264 static void
8265 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
8266 {
8267 	if (flags & ZDB_FLAG_BSWAP)
8268 		byteswap_uint64_array(buf, size);
8269 	VERIFY(write(fileno(stdout), buf, size) == size);
8270 }
8271 
8272 static void
8273 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
8274 {
8275 	uint64_t *d = (uint64_t *)buf;
8276 	unsigned nwords = size / sizeof (uint64_t);
8277 	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
8278 	unsigned i, j;
8279 	const char *hdr;
8280 	char *c;
8281 
8282 
8283 	if (do_bswap)
8284 		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
8285 	else
8286 		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
8287 
8288 	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
8289 
8290 #ifdef _LITTLE_ENDIAN
8291 	/* correct the endianness */
8292 	do_bswap = !do_bswap;
8293 #endif
8294 	for (i = 0; i < nwords; i += 2) {
8295 		(void) printf("%06llx:  %016llx  %016llx  ",
8296 		    (u_longlong_t)(i * sizeof (uint64_t)),
8297 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
8298 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
8299 
8300 		c = (char *)&d[i];
8301 		for (j = 0; j < 2 * sizeof (uint64_t); j++)
8302 			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
8303 		(void) printf("\n");
8304 	}
8305 }
8306 
8307 /*
8308  * There are two acceptable formats:
8309  *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
8310  *	child[.child]*    - For example: 0.1.1
8311  *
8312  * The second form can be used to specify arbitrary vdevs anywhere
8313  * in the hierarchy.  For example, in a pool with a mirror of
8314  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
8315  */
8316 static vdev_t *
8317 zdb_vdev_lookup(vdev_t *vdev, const char *path)
8318 {
8319 	char *s, *p, *q;
8320 	unsigned i;
8321 
8322 	if (vdev == NULL)
8323 		return (NULL);
8324 
8325 	/* First, assume the x.x.x.x format */
8326 	i = strtoul(path, &s, 10);
8327 	if (s == path || (s && *s != '.' && *s != '\0'))
8328 		goto name;
8329 	if (i >= vdev->vdev_children)
8330 		return (NULL);
8331 
8332 	vdev = vdev->vdev_child[i];
8333 	if (s && *s == '\0')
8334 		return (vdev);
8335 	return (zdb_vdev_lookup(vdev, s+1));
8336 
8337 name:
8338 	for (i = 0; i < vdev->vdev_children; i++) {
8339 		vdev_t *vc = vdev->vdev_child[i];
8340 
8341 		if (vc->vdev_path == NULL) {
8342 			vc = zdb_vdev_lookup(vc, path);
8343 			if (vc == NULL)
8344 				continue;
8345 			else
8346 				return (vc);
8347 		}
8348 
8349 		p = strrchr(vc->vdev_path, '/');
8350 		p = p ? p + 1 : vc->vdev_path;
8351 		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
8352 
8353 		if (strcmp(vc->vdev_path, path) == 0)
8354 			return (vc);
8355 		if (strcmp(p, path) == 0)
8356 			return (vc);
8357 		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
8358 			return (vc);
8359 	}
8360 
8361 	return (NULL);
8362 }
8363 
8364 static int
8365 name_from_objset_id(spa_t *spa, uint64_t objset_id, char *outstr)
8366 {
8367 	dsl_dataset_t *ds;
8368 
8369 	dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
8370 	int error = dsl_dataset_hold_obj(spa->spa_dsl_pool, objset_id,
8371 	    NULL, &ds);
8372 	if (error != 0) {
8373 		(void) fprintf(stderr, "failed to hold objset %llu: %s\n",
8374 		    (u_longlong_t)objset_id, strerror(error));
8375 		dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
8376 		return (error);
8377 	}
8378 	dsl_dataset_name(ds, outstr);
8379 	dsl_dataset_rele(ds, NULL);
8380 	dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
8381 	return (0);
8382 }
8383 
8384 static boolean_t
8385 zdb_parse_block_sizes(char *sizes, uint64_t *lsize, uint64_t *psize)
8386 {
8387 	char *s0, *s1, *tmp = NULL;
8388 
8389 	if (sizes == NULL)
8390 		return (B_FALSE);
8391 
8392 	s0 = strtok_r(sizes, "/", &tmp);
8393 	if (s0 == NULL)
8394 		return (B_FALSE);
8395 	s1 = strtok_r(NULL, "/", &tmp);
8396 	*lsize = strtoull(s0, NULL, 16);
8397 	*psize = s1 ? strtoull(s1, NULL, 16) : *lsize;
8398 	return (*lsize >= *psize && *psize > 0);
8399 }
8400 
8401 #define	ZIO_COMPRESS_MASK(alg)	(1ULL << (ZIO_COMPRESS_##alg))
8402 
8403 static boolean_t
8404 zdb_decompress_block(abd_t *pabd, void *buf, void *lbuf, uint64_t lsize,
8405     uint64_t psize, int flags)
8406 {
8407 	(void) buf;
8408 	boolean_t exceeded = B_FALSE;
8409 	/*
8410 	 * We don't know how the data was compressed, so just try
8411 	 * every decompress function at every inflated blocksize.
8412 	 */
8413 	void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
8414 	int cfuncs[ZIO_COMPRESS_FUNCTIONS] = { 0 };
8415 	int *cfuncp = cfuncs;
8416 	uint64_t maxlsize = SPA_MAXBLOCKSIZE;
8417 	uint64_t mask = ZIO_COMPRESS_MASK(ON) | ZIO_COMPRESS_MASK(OFF) |
8418 	    ZIO_COMPRESS_MASK(INHERIT) | ZIO_COMPRESS_MASK(EMPTY) |
8419 	    (getenv("ZDB_NO_ZLE") ? ZIO_COMPRESS_MASK(ZLE) : 0);
8420 	*cfuncp++ = ZIO_COMPRESS_LZ4;
8421 	*cfuncp++ = ZIO_COMPRESS_LZJB;
8422 	mask |= ZIO_COMPRESS_MASK(LZ4) | ZIO_COMPRESS_MASK(LZJB);
8423 	for (int c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++)
8424 		if (((1ULL << c) & mask) == 0)
8425 			*cfuncp++ = c;
8426 
8427 	/*
8428 	 * On the one hand, with SPA_MAXBLOCKSIZE at 16MB, this
8429 	 * could take a while and we should let the user know
8430 	 * we are not stuck.  On the other hand, printing progress
8431 	 * info gets old after a while.  User can specify 'v' flag
8432 	 * to see the progression.
8433 	 */
8434 	if (lsize == psize)
8435 		lsize += SPA_MINBLOCKSIZE;
8436 	else
8437 		maxlsize = lsize;
8438 	for (; lsize <= maxlsize; lsize += SPA_MINBLOCKSIZE) {
8439 		for (cfuncp = cfuncs; *cfuncp; cfuncp++) {
8440 			if (flags & ZDB_FLAG_VERBOSE) {
8441 				(void) fprintf(stderr,
8442 				    "Trying %05llx -> %05llx (%s)\n",
8443 				    (u_longlong_t)psize,
8444 				    (u_longlong_t)lsize,
8445 				    zio_compress_table[*cfuncp].\
8446 				    ci_name);
8447 			}
8448 
8449 			/*
8450 			 * We randomize lbuf2, and decompress to both
8451 			 * lbuf and lbuf2. This way, we will know if
8452 			 * decompression fill exactly to lsize.
8453 			 */
8454 			VERIFY0(random_get_pseudo_bytes(lbuf2, lsize));
8455 
8456 			if (zio_decompress_data(*cfuncp, pabd,
8457 			    lbuf, psize, lsize, NULL) == 0 &&
8458 			    zio_decompress_data(*cfuncp, pabd,
8459 			    lbuf2, psize, lsize, NULL) == 0 &&
8460 			    memcmp(lbuf, lbuf2, lsize) == 0)
8461 				break;
8462 		}
8463 		if (*cfuncp != 0)
8464 			break;
8465 	}
8466 	umem_free(lbuf2, SPA_MAXBLOCKSIZE);
8467 
8468 	if (lsize > maxlsize) {
8469 		exceeded = B_TRUE;
8470 	}
8471 	if (*cfuncp == ZIO_COMPRESS_ZLE) {
8472 		printf("\nZLE decompression was selected. If you "
8473 		    "suspect the results are wrong,\ntry avoiding ZLE "
8474 		    "by setting and exporting ZDB_NO_ZLE=\"true\"\n");
8475 	}
8476 
8477 	return (exceeded);
8478 }
8479 
8480 /*
8481  * Read a block from a pool and print it out.  The syntax of the
8482  * block descriptor is:
8483  *
8484  *	pool:vdev_specifier:offset:[lsize/]psize[:flags]
8485  *
8486  *	pool           - The name of the pool you wish to read from
8487  *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
8488  *	offset         - offset, in hex, in bytes
8489  *	size           - Amount of data to read, in hex, in bytes
8490  *	flags          - A string of characters specifying options
8491  *		 b: Decode a blkptr at given offset within block
8492  *		 c: Calculate and display checksums
8493  *		 d: Decompress data before dumping
8494  *		 e: Byteswap data before dumping
8495  *		 g: Display data as a gang block header
8496  *		 i: Display as an indirect block
8497  *		 r: Dump raw data to stdout
8498  *		 v: Verbose
8499  *
8500  */
8501 static void
8502 zdb_read_block(char *thing, spa_t *spa)
8503 {
8504 	blkptr_t blk, *bp = &blk;
8505 	dva_t *dva = bp->blk_dva;
8506 	int flags = 0;
8507 	uint64_t offset = 0, psize = 0, lsize = 0, blkptr_offset = 0;
8508 	zio_t *zio;
8509 	vdev_t *vd;
8510 	abd_t *pabd;
8511 	void *lbuf, *buf;
8512 	char *s, *p, *dup, *flagstr, *sizes, *tmp = NULL;
8513 	const char *vdev, *errmsg = NULL;
8514 	int i, error;
8515 	boolean_t borrowed = B_FALSE, found = B_FALSE;
8516 
8517 	dup = strdup(thing);
8518 	s = strtok_r(dup, ":", &tmp);
8519 	vdev = s ?: "";
8520 	s = strtok_r(NULL, ":", &tmp);
8521 	offset = strtoull(s ? s : "", NULL, 16);
8522 	sizes = strtok_r(NULL, ":", &tmp);
8523 	s = strtok_r(NULL, ":", &tmp);
8524 	flagstr = strdup(s ?: "");
8525 
8526 	if (!zdb_parse_block_sizes(sizes, &lsize, &psize))
8527 		errmsg = "invalid size(s)";
8528 	if (!IS_P2ALIGNED(psize, DEV_BSIZE) || !IS_P2ALIGNED(lsize, DEV_BSIZE))
8529 		errmsg = "size must be a multiple of sector size";
8530 	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
8531 		errmsg = "offset must be a multiple of sector size";
8532 	if (errmsg) {
8533 		(void) printf("Invalid block specifier: %s  - %s\n",
8534 		    thing, errmsg);
8535 		goto done;
8536 	}
8537 
8538 	tmp = NULL;
8539 	for (s = strtok_r(flagstr, ":", &tmp);
8540 	    s != NULL;
8541 	    s = strtok_r(NULL, ":", &tmp)) {
8542 		for (i = 0; i < strlen(flagstr); i++) {
8543 			int bit = flagbits[(uchar_t)flagstr[i]];
8544 
8545 			if (bit == 0) {
8546 				(void) printf("***Ignoring flag: %c\n",
8547 				    (uchar_t)flagstr[i]);
8548 				continue;
8549 			}
8550 			found = B_TRUE;
8551 			flags |= bit;
8552 
8553 			p = &flagstr[i + 1];
8554 			if (*p != ':' && *p != '\0') {
8555 				int j = 0, nextbit = flagbits[(uchar_t)*p];
8556 				char *end, offstr[8] = { 0 };
8557 				if ((bit == ZDB_FLAG_PRINT_BLKPTR) &&
8558 				    (nextbit == 0)) {
8559 					/* look ahead to isolate the offset */
8560 					while (nextbit == 0 &&
8561 					    strchr(flagbitstr, *p) == NULL) {
8562 						offstr[j] = *p;
8563 						j++;
8564 						if (i + j > strlen(flagstr))
8565 							break;
8566 						p++;
8567 						nextbit = flagbits[(uchar_t)*p];
8568 					}
8569 					blkptr_offset = strtoull(offstr, &end,
8570 					    16);
8571 					i += j;
8572 				} else if (nextbit == 0) {
8573 					(void) printf("***Ignoring flag arg:"
8574 					    " '%c'\n", (uchar_t)*p);
8575 				}
8576 			}
8577 		}
8578 	}
8579 	if (blkptr_offset % sizeof (blkptr_t)) {
8580 		printf("Block pointer offset 0x%llx "
8581 		    "must be divisible by 0x%x\n",
8582 		    (longlong_t)blkptr_offset, (int)sizeof (blkptr_t));
8583 		goto done;
8584 	}
8585 	if (found == B_FALSE && strlen(flagstr) > 0) {
8586 		printf("Invalid flag arg: '%s'\n", flagstr);
8587 		goto done;
8588 	}
8589 
8590 	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
8591 	if (vd == NULL) {
8592 		(void) printf("***Invalid vdev: %s\n", vdev);
8593 		goto done;
8594 	} else {
8595 		if (vd->vdev_path)
8596 			(void) fprintf(stderr, "Found vdev: %s\n",
8597 			    vd->vdev_path);
8598 		else
8599 			(void) fprintf(stderr, "Found vdev type: %s\n",
8600 			    vd->vdev_ops->vdev_op_type);
8601 	}
8602 
8603 	pabd = abd_alloc_for_io(SPA_MAXBLOCKSIZE, B_FALSE);
8604 	lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
8605 
8606 	BP_ZERO(bp);
8607 
8608 	DVA_SET_VDEV(&dva[0], vd->vdev_id);
8609 	DVA_SET_OFFSET(&dva[0], offset);
8610 	DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
8611 	DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
8612 
8613 	BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
8614 
8615 	BP_SET_LSIZE(bp, lsize);
8616 	BP_SET_PSIZE(bp, psize);
8617 	BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
8618 	BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
8619 	BP_SET_TYPE(bp, DMU_OT_NONE);
8620 	BP_SET_LEVEL(bp, 0);
8621 	BP_SET_DEDUP(bp, 0);
8622 	BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
8623 
8624 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8625 	zio = zio_root(spa, NULL, NULL, 0);
8626 
8627 	if (vd == vd->vdev_top) {
8628 		/*
8629 		 * Treat this as a normal block read.
8630 		 */
8631 		zio_nowait(zio_read(zio, spa, bp, pabd, psize, NULL, NULL,
8632 		    ZIO_PRIORITY_SYNC_READ,
8633 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
8634 	} else {
8635 		/*
8636 		 * Treat this as a vdev child I/O.
8637 		 */
8638 		zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pabd,
8639 		    psize, ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
8640 		    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
8641 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW | ZIO_FLAG_OPTIONAL,
8642 		    NULL, NULL));
8643 	}
8644 
8645 	error = zio_wait(zio);
8646 	spa_config_exit(spa, SCL_STATE, FTAG);
8647 
8648 	if (error) {
8649 		(void) printf("Read of %s failed, error: %d\n", thing, error);
8650 		goto out;
8651 	}
8652 
8653 	uint64_t orig_lsize = lsize;
8654 	buf = lbuf;
8655 	if (flags & ZDB_FLAG_DECOMPRESS) {
8656 		boolean_t failed = zdb_decompress_block(pabd, buf, lbuf,
8657 		    lsize, psize, flags);
8658 		if (failed) {
8659 			(void) printf("Decompress of %s failed\n", thing);
8660 			goto out;
8661 		}
8662 	} else {
8663 		buf = abd_borrow_buf_copy(pabd, lsize);
8664 		borrowed = B_TRUE;
8665 	}
8666 	/*
8667 	 * Try to detect invalid block pointer.  If invalid, try
8668 	 * decompressing.
8669 	 */
8670 	if ((flags & ZDB_FLAG_PRINT_BLKPTR || flags & ZDB_FLAG_INDIRECT) &&
8671 	    !(flags & ZDB_FLAG_DECOMPRESS)) {
8672 		const blkptr_t *b = (const blkptr_t *)(void *)
8673 		    ((uintptr_t)buf + (uintptr_t)blkptr_offset);
8674 		if (zfs_blkptr_verify(spa, b,
8675 		    BLK_CONFIG_NEEDED, BLK_VERIFY_ONLY) == B_FALSE) {
8676 			abd_return_buf_copy(pabd, buf, lsize);
8677 			borrowed = B_FALSE;
8678 			buf = lbuf;
8679 			boolean_t failed = zdb_decompress_block(pabd, buf,
8680 			    lbuf, lsize, psize, flags);
8681 			b = (const blkptr_t *)(void *)
8682 			    ((uintptr_t)buf + (uintptr_t)blkptr_offset);
8683 			if (failed || zfs_blkptr_verify(spa, b,
8684 			    BLK_CONFIG_NEEDED, BLK_VERIFY_LOG) == B_FALSE) {
8685 				printf("invalid block pointer at this DVA\n");
8686 				goto out;
8687 			}
8688 		}
8689 	}
8690 
8691 	if (flags & ZDB_FLAG_PRINT_BLKPTR)
8692 		zdb_print_blkptr((blkptr_t *)(void *)
8693 		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
8694 	else if (flags & ZDB_FLAG_RAW)
8695 		zdb_dump_block_raw(buf, lsize, flags);
8696 	else if (flags & ZDB_FLAG_INDIRECT)
8697 		zdb_dump_indirect((blkptr_t *)buf,
8698 		    orig_lsize / sizeof (blkptr_t), flags);
8699 	else if (flags & ZDB_FLAG_GBH)
8700 		zdb_dump_gbh(buf, flags);
8701 	else
8702 		zdb_dump_block(thing, buf, lsize, flags);
8703 
8704 	/*
8705 	 * If :c was specified, iterate through the checksum table to
8706 	 * calculate and display each checksum for our specified
8707 	 * DVA and length.
8708 	 */
8709 	if ((flags & ZDB_FLAG_CHECKSUM) && !(flags & ZDB_FLAG_RAW) &&
8710 	    !(flags & ZDB_FLAG_GBH)) {
8711 		zio_t *czio;
8712 		(void) printf("\n");
8713 		for (enum zio_checksum ck = ZIO_CHECKSUM_LABEL;
8714 		    ck < ZIO_CHECKSUM_FUNCTIONS; ck++) {
8715 
8716 			if ((zio_checksum_table[ck].ci_flags &
8717 			    ZCHECKSUM_FLAG_EMBEDDED) ||
8718 			    ck == ZIO_CHECKSUM_NOPARITY) {
8719 				continue;
8720 			}
8721 			BP_SET_CHECKSUM(bp, ck);
8722 			spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8723 			czio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
8724 			if (vd == vd->vdev_top) {
8725 				zio_nowait(zio_read(czio, spa, bp, pabd, psize,
8726 				    NULL, NULL,
8727 				    ZIO_PRIORITY_SYNC_READ,
8728 				    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW |
8729 				    ZIO_FLAG_DONT_RETRY, NULL));
8730 			} else {
8731 				zio_nowait(zio_vdev_child_io(czio, bp, vd,
8732 				    offset, pabd, psize, ZIO_TYPE_READ,
8733 				    ZIO_PRIORITY_SYNC_READ,
8734 				    ZIO_FLAG_DONT_PROPAGATE |
8735 				    ZIO_FLAG_DONT_RETRY |
8736 				    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW |
8737 				    ZIO_FLAG_SPECULATIVE |
8738 				    ZIO_FLAG_OPTIONAL, NULL, NULL));
8739 			}
8740 			error = zio_wait(czio);
8741 			if (error == 0 || error == ECKSUM) {
8742 				zio_t *ck_zio = zio_null(NULL, spa, NULL,
8743 				    NULL, NULL, 0);
8744 				ck_zio->io_offset =
8745 				    DVA_GET_OFFSET(&bp->blk_dva[0]);
8746 				ck_zio->io_bp = bp;
8747 				zio_checksum_compute(ck_zio, ck, pabd, lsize);
8748 				printf(
8749 				    "%12s\t"
8750 				    "cksum=%016llx:%016llx:%016llx:%016llx\n",
8751 				    zio_checksum_table[ck].ci_name,
8752 				    (u_longlong_t)bp->blk_cksum.zc_word[0],
8753 				    (u_longlong_t)bp->blk_cksum.zc_word[1],
8754 				    (u_longlong_t)bp->blk_cksum.zc_word[2],
8755 				    (u_longlong_t)bp->blk_cksum.zc_word[3]);
8756 				zio_wait(ck_zio);
8757 			} else {
8758 				printf("error %d reading block\n", error);
8759 			}
8760 			spa_config_exit(spa, SCL_STATE, FTAG);
8761 		}
8762 	}
8763 
8764 	if (borrowed)
8765 		abd_return_buf_copy(pabd, buf, lsize);
8766 
8767 out:
8768 	abd_free(pabd);
8769 	umem_free(lbuf, SPA_MAXBLOCKSIZE);
8770 done:
8771 	free(flagstr);
8772 	free(dup);
8773 }
8774 
8775 static void
8776 zdb_embedded_block(char *thing)
8777 {
8778 	blkptr_t bp = {{{{0}}}};
8779 	unsigned long long *words = (void *)&bp;
8780 	char *buf;
8781 	int err;
8782 
8783 	err = sscanf(thing, "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx:"
8784 	    "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx",
8785 	    words + 0, words + 1, words + 2, words + 3,
8786 	    words + 4, words + 5, words + 6, words + 7,
8787 	    words + 8, words + 9, words + 10, words + 11,
8788 	    words + 12, words + 13, words + 14, words + 15);
8789 	if (err != 16) {
8790 		(void) fprintf(stderr, "invalid input format\n");
8791 		exit(1);
8792 	}
8793 	ASSERT3U(BPE_GET_LSIZE(&bp), <=, SPA_MAXBLOCKSIZE);
8794 	buf = malloc(SPA_MAXBLOCKSIZE);
8795 	if (buf == NULL) {
8796 		(void) fprintf(stderr, "out of memory\n");
8797 		exit(1);
8798 	}
8799 	err = decode_embedded_bp(&bp, buf, BPE_GET_LSIZE(&bp));
8800 	if (err != 0) {
8801 		(void) fprintf(stderr, "decode failed: %u\n", err);
8802 		exit(1);
8803 	}
8804 	zdb_dump_block_raw(buf, BPE_GET_LSIZE(&bp), 0);
8805 	free(buf);
8806 }
8807 
8808 /* check for valid hex or decimal numeric string */
8809 static boolean_t
8810 zdb_numeric(char *str)
8811 {
8812 	int i = 0;
8813 
8814 	if (strlen(str) == 0)
8815 		return (B_FALSE);
8816 	if (strncmp(str, "0x", 2) == 0 || strncmp(str, "0X", 2) == 0)
8817 		i = 2;
8818 	for (; i < strlen(str); i++) {
8819 		if (!isxdigit(str[i]))
8820 			return (B_FALSE);
8821 	}
8822 	return (B_TRUE);
8823 }
8824 
8825 int
8826 main(int argc, char **argv)
8827 {
8828 	int c;
8829 	spa_t *spa = NULL;
8830 	objset_t *os = NULL;
8831 	int dump_all = 1;
8832 	int verbose = 0;
8833 	int error = 0;
8834 	char **searchdirs = NULL;
8835 	int nsearch = 0;
8836 	char *target, *target_pool, dsname[ZFS_MAX_DATASET_NAME_LEN];
8837 	nvlist_t *policy = NULL;
8838 	uint64_t max_txg = UINT64_MAX;
8839 	int64_t objset_id = -1;
8840 	uint64_t object;
8841 	int flags = ZFS_IMPORT_MISSING_LOG;
8842 	int rewind = ZPOOL_NEVER_REWIND;
8843 	char *spa_config_path_env, *objset_str;
8844 	boolean_t target_is_spa = B_TRUE, dataset_lookup = B_FALSE;
8845 	nvlist_t *cfg = NULL;
8846 
8847 	dprintf_setup(&argc, argv);
8848 
8849 	/*
8850 	 * If there is an environment variable SPA_CONFIG_PATH it overrides
8851 	 * default spa_config_path setting. If -U flag is specified it will
8852 	 * override this environment variable settings once again.
8853 	 */
8854 	spa_config_path_env = getenv("SPA_CONFIG_PATH");
8855 	if (spa_config_path_env != NULL)
8856 		spa_config_path = spa_config_path_env;
8857 
8858 	/*
8859 	 * For performance reasons, we set this tunable down. We do so before
8860 	 * the arg parsing section so that the user can override this value if
8861 	 * they choose.
8862 	 */
8863 	zfs_btree_verify_intensity = 3;
8864 
8865 	struct option long_options[] = {
8866 		{"ignore-assertions",	no_argument,		NULL, 'A'},
8867 		{"block-stats",		no_argument,		NULL, 'b'},
8868 		{"backup",		no_argument,		NULL, 'B'},
8869 		{"checksum",		no_argument,		NULL, 'c'},
8870 		{"config",		no_argument,		NULL, 'C'},
8871 		{"datasets",		no_argument,		NULL, 'd'},
8872 		{"dedup-stats",		no_argument,		NULL, 'D'},
8873 		{"exported",		no_argument,		NULL, 'e'},
8874 		{"embedded-block-pointer",	no_argument,	NULL, 'E'},
8875 		{"automatic-rewind",	no_argument,		NULL, 'F'},
8876 		{"dump-debug-msg",	no_argument,		NULL, 'G'},
8877 		{"history",		no_argument,		NULL, 'h'},
8878 		{"intent-logs",		no_argument,		NULL, 'i'},
8879 		{"inflight",		required_argument,	NULL, 'I'},
8880 		{"checkpointed-state",	no_argument,		NULL, 'k'},
8881 		{"key",			required_argument,	NULL, 'K'},
8882 		{"label",		no_argument,		NULL, 'l'},
8883 		{"disable-leak-tracking",	no_argument,	NULL, 'L'},
8884 		{"metaslabs",		no_argument,		NULL, 'm'},
8885 		{"metaslab-groups",	no_argument,		NULL, 'M'},
8886 		{"numeric",		no_argument,		NULL, 'N'},
8887 		{"option",		required_argument,	NULL, 'o'},
8888 		{"object-lookups",	no_argument,		NULL, 'O'},
8889 		{"path",		required_argument,	NULL, 'p'},
8890 		{"parseable",		no_argument,		NULL, 'P'},
8891 		{"skip-label",		no_argument,		NULL, 'q'},
8892 		{"copy-object",		no_argument,		NULL, 'r'},
8893 		{"read-block",		no_argument,		NULL, 'R'},
8894 		{"io-stats",		no_argument,		NULL, 's'},
8895 		{"simulate-dedup",	no_argument,		NULL, 'S'},
8896 		{"txg",			required_argument,	NULL, 't'},
8897 		{"uberblock",		no_argument,		NULL, 'u'},
8898 		{"cachefile",		required_argument,	NULL, 'U'},
8899 		{"verbose",		no_argument,		NULL, 'v'},
8900 		{"verbatim",		no_argument,		NULL, 'V'},
8901 		{"dump-blocks",		required_argument,	NULL, 'x'},
8902 		{"extreme-rewind",	no_argument,		NULL, 'X'},
8903 		{"all-reconstruction",	no_argument,		NULL, 'Y'},
8904 		{"livelist",		no_argument,		NULL, 'y'},
8905 		{"zstd-headers",	no_argument,		NULL, 'Z'},
8906 		{0, 0, 0, 0}
8907 	};
8908 
8909 	while ((c = getopt_long(argc, argv,
8910 	    "AbBcCdDeEFGhiI:kK:lLmMNo:Op:PqrRsSt:uU:vVx:XYyZ",
8911 	    long_options, NULL)) != -1) {
8912 		switch (c) {
8913 		case 'b':
8914 		case 'B':
8915 		case 'c':
8916 		case 'C':
8917 		case 'd':
8918 		case 'D':
8919 		case 'E':
8920 		case 'G':
8921 		case 'h':
8922 		case 'i':
8923 		case 'l':
8924 		case 'm':
8925 		case 'M':
8926 		case 'N':
8927 		case 'O':
8928 		case 'r':
8929 		case 'R':
8930 		case 's':
8931 		case 'S':
8932 		case 'u':
8933 		case 'y':
8934 		case 'Z':
8935 			dump_opt[c]++;
8936 			dump_all = 0;
8937 			break;
8938 		case 'A':
8939 		case 'e':
8940 		case 'F':
8941 		case 'k':
8942 		case 'L':
8943 		case 'P':
8944 		case 'q':
8945 		case 'X':
8946 			dump_opt[c]++;
8947 			break;
8948 		case 'Y':
8949 			zfs_reconstruct_indirect_combinations_max = INT_MAX;
8950 			zfs_deadman_enabled = 0;
8951 			break;
8952 		/* NB: Sort single match options below. */
8953 		case 'I':
8954 			max_inflight_bytes = strtoull(optarg, NULL, 0);
8955 			if (max_inflight_bytes == 0) {
8956 				(void) fprintf(stderr, "maximum number "
8957 				    "of inflight bytes must be greater "
8958 				    "than 0\n");
8959 				usage();
8960 			}
8961 			break;
8962 		case 'K':
8963 			dump_opt[c]++;
8964 			key_material = strdup(optarg);
8965 			/* redact key material in process table */
8966 			while (*optarg != '\0') { *optarg++ = '*'; }
8967 			break;
8968 		case 'o':
8969 			error = set_global_var(optarg);
8970 			if (error != 0)
8971 				usage();
8972 			break;
8973 		case 'p':
8974 			if (searchdirs == NULL) {
8975 				searchdirs = umem_alloc(sizeof (char *),
8976 				    UMEM_NOFAIL);
8977 			} else {
8978 				char **tmp = umem_alloc((nsearch + 1) *
8979 				    sizeof (char *), UMEM_NOFAIL);
8980 				memcpy(tmp, searchdirs, nsearch *
8981 				    sizeof (char *));
8982 				umem_free(searchdirs,
8983 				    nsearch * sizeof (char *));
8984 				searchdirs = tmp;
8985 			}
8986 			searchdirs[nsearch++] = optarg;
8987 			break;
8988 		case 't':
8989 			max_txg = strtoull(optarg, NULL, 0);
8990 			if (max_txg < TXG_INITIAL) {
8991 				(void) fprintf(stderr, "incorrect txg "
8992 				    "specified: %s\n", optarg);
8993 				usage();
8994 			}
8995 			break;
8996 		case 'U':
8997 			spa_config_path = optarg;
8998 			if (spa_config_path[0] != '/') {
8999 				(void) fprintf(stderr,
9000 				    "cachefile must be an absolute path "
9001 				    "(i.e. start with a slash)\n");
9002 				usage();
9003 			}
9004 			break;
9005 		case 'v':
9006 			verbose++;
9007 			break;
9008 		case 'V':
9009 			flags = ZFS_IMPORT_VERBATIM;
9010 			break;
9011 		case 'x':
9012 			vn_dumpdir = optarg;
9013 			break;
9014 		default:
9015 			usage();
9016 			break;
9017 		}
9018 	}
9019 
9020 	if (!dump_opt['e'] && searchdirs != NULL) {
9021 		(void) fprintf(stderr, "-p option requires use of -e\n");
9022 		usage();
9023 	}
9024 #if defined(_LP64)
9025 	/*
9026 	 * ZDB does not typically re-read blocks; therefore limit the ARC
9027 	 * to 256 MB, which can be used entirely for metadata.
9028 	 */
9029 	zfs_arc_min = 2ULL << SPA_MAXBLOCKSHIFT;
9030 	zfs_arc_max = 256 * 1024 * 1024;
9031 #endif
9032 
9033 	/*
9034 	 * "zdb -c" uses checksum-verifying scrub i/os which are async reads.
9035 	 * "zdb -b" uses traversal prefetch which uses async reads.
9036 	 * For good performance, let several of them be active at once.
9037 	 */
9038 	zfs_vdev_async_read_max_active = 10;
9039 
9040 	/*
9041 	 * Disable reference tracking for better performance.
9042 	 */
9043 	reference_tracking_enable = B_FALSE;
9044 
9045 	/*
9046 	 * Do not fail spa_load when spa_load_verify fails. This is needed
9047 	 * to load non-idle pools.
9048 	 */
9049 	spa_load_verify_dryrun = B_TRUE;
9050 
9051 	/*
9052 	 * ZDB should have ability to read spacemaps.
9053 	 */
9054 	spa_mode_readable_spacemaps = B_TRUE;
9055 
9056 	kernel_init(SPA_MODE_READ);
9057 
9058 	if (dump_all)
9059 		verbose = MAX(verbose, 1);
9060 
9061 	for (c = 0; c < 256; c++) {
9062 		if (dump_all && strchr("ABeEFkKlLNOPrRSXy", c) == NULL)
9063 			dump_opt[c] = 1;
9064 		if (dump_opt[c])
9065 			dump_opt[c] += verbose;
9066 	}
9067 
9068 	libspl_set_assert_ok((dump_opt['A'] == 1) || (dump_opt['A'] > 2));
9069 	zfs_recover = (dump_opt['A'] > 1);
9070 
9071 	argc -= optind;
9072 	argv += optind;
9073 	if (argc < 2 && dump_opt['R'])
9074 		usage();
9075 
9076 	if (dump_opt['E']) {
9077 		if (argc != 1)
9078 			usage();
9079 		zdb_embedded_block(argv[0]);
9080 		return (0);
9081 	}
9082 
9083 	if (argc < 1) {
9084 		if (!dump_opt['e'] && dump_opt['C']) {
9085 			dump_cachefile(spa_config_path);
9086 			return (0);
9087 		}
9088 		usage();
9089 	}
9090 
9091 	if (dump_opt['l'])
9092 		return (dump_label(argv[0]));
9093 
9094 	if (dump_opt['O']) {
9095 		if (argc != 2)
9096 			usage();
9097 		dump_opt['v'] = verbose + 3;
9098 		return (dump_path(argv[0], argv[1], NULL));
9099 	}
9100 	if (dump_opt['r']) {
9101 		target_is_spa = B_FALSE;
9102 		if (argc != 3)
9103 			usage();
9104 		dump_opt['v'] = verbose;
9105 		error = dump_path(argv[0], argv[1], &object);
9106 		if (error != 0)
9107 			fatal("internal error: %s", strerror(error));
9108 	}
9109 
9110 	if (dump_opt['X'] || dump_opt['F'])
9111 		rewind = ZPOOL_DO_REWIND |
9112 		    (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
9113 
9114 	/* -N implies -d */
9115 	if (dump_opt['N'] && dump_opt['d'] == 0)
9116 		dump_opt['d'] = dump_opt['N'];
9117 
9118 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
9119 	    nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, max_txg) != 0 ||
9120 	    nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY, rewind) != 0)
9121 		fatal("internal error: %s", strerror(ENOMEM));
9122 
9123 	error = 0;
9124 	target = argv[0];
9125 
9126 	if (strpbrk(target, "/@") != NULL) {
9127 		size_t targetlen;
9128 
9129 		target_pool = strdup(target);
9130 		*strpbrk(target_pool, "/@") = '\0';
9131 
9132 		target_is_spa = B_FALSE;
9133 		targetlen = strlen(target);
9134 		if (targetlen && target[targetlen - 1] == '/')
9135 			target[targetlen - 1] = '\0';
9136 
9137 		/*
9138 		 * See if an objset ID was supplied (-d <pool>/<objset ID>).
9139 		 * To disambiguate tank/100, consider the 100 as objsetID
9140 		 * if -N was given, otherwise 100 is an objsetID iff
9141 		 * tank/100 as a named dataset fails on lookup.
9142 		 */
9143 		objset_str = strchr(target, '/');
9144 		if (objset_str && strlen(objset_str) > 1 &&
9145 		    zdb_numeric(objset_str + 1)) {
9146 			char *endptr;
9147 			errno = 0;
9148 			objset_str++;
9149 			objset_id = strtoull(objset_str, &endptr, 0);
9150 			/* dataset 0 is the same as opening the pool */
9151 			if (errno == 0 && endptr != objset_str &&
9152 			    objset_id != 0) {
9153 				if (dump_opt['N'])
9154 					dataset_lookup = B_TRUE;
9155 			}
9156 			/* normal dataset name not an objset ID */
9157 			if (endptr == objset_str) {
9158 				objset_id = -1;
9159 			}
9160 		} else if (objset_str && !zdb_numeric(objset_str + 1) &&
9161 		    dump_opt['N']) {
9162 			printf("Supply a numeric objset ID with -N\n");
9163 			exit(1);
9164 		}
9165 	} else {
9166 		target_pool = target;
9167 	}
9168 
9169 	if (dump_opt['e']) {
9170 		importargs_t args = { 0 };
9171 
9172 		args.paths = nsearch;
9173 		args.path = searchdirs;
9174 		args.can_be_active = B_TRUE;
9175 
9176 		libpc_handle_t lpch = {
9177 			.lpc_lib_handle = NULL,
9178 			.lpc_ops = &libzpool_config_ops,
9179 			.lpc_printerr = B_TRUE
9180 		};
9181 		error = zpool_find_config(&lpch, target_pool, &cfg, &args);
9182 
9183 		if (error == 0) {
9184 
9185 			if (nvlist_add_nvlist(cfg,
9186 			    ZPOOL_LOAD_POLICY, policy) != 0) {
9187 				fatal("can't open '%s': %s",
9188 				    target, strerror(ENOMEM));
9189 			}
9190 
9191 			if (dump_opt['C'] > 1) {
9192 				(void) printf("\nConfiguration for import:\n");
9193 				dump_nvlist(cfg, 8);
9194 			}
9195 
9196 			/*
9197 			 * Disable the activity check to allow examination of
9198 			 * active pools.
9199 			 */
9200 			error = spa_import(target_pool, cfg, NULL,
9201 			    flags | ZFS_IMPORT_SKIP_MMP);
9202 		}
9203 	}
9204 
9205 	if (searchdirs != NULL) {
9206 		umem_free(searchdirs, nsearch * sizeof (char *));
9207 		searchdirs = NULL;
9208 	}
9209 
9210 	/*
9211 	 * import_checkpointed_state makes the assumption that the
9212 	 * target pool that we pass it is already part of the spa
9213 	 * namespace. Because of that we need to make sure to call
9214 	 * it always after the -e option has been processed, which
9215 	 * imports the pool to the namespace if it's not in the
9216 	 * cachefile.
9217 	 */
9218 	char *checkpoint_pool = NULL;
9219 	char *checkpoint_target = NULL;
9220 	if (dump_opt['k']) {
9221 		checkpoint_pool = import_checkpointed_state(target, cfg,
9222 		    &checkpoint_target);
9223 
9224 		if (checkpoint_target != NULL)
9225 			target = checkpoint_target;
9226 	}
9227 
9228 	if (cfg != NULL) {
9229 		nvlist_free(cfg);
9230 		cfg = NULL;
9231 	}
9232 
9233 	if (target_pool != target)
9234 		free(target_pool);
9235 
9236 	if (error == 0) {
9237 		if (dump_opt['k'] && (target_is_spa || dump_opt['R'])) {
9238 			ASSERT(checkpoint_pool != NULL);
9239 			ASSERT(checkpoint_target == NULL);
9240 
9241 			error = spa_open(checkpoint_pool, &spa, FTAG);
9242 			if (error != 0) {
9243 				fatal("Tried to open pool \"%s\" but "
9244 				    "spa_open() failed with error %d\n",
9245 				    checkpoint_pool, error);
9246 			}
9247 
9248 		} else if (target_is_spa || dump_opt['R'] || dump_opt['B'] ||
9249 		    objset_id == 0) {
9250 			zdb_set_skip_mmp(target);
9251 			error = spa_open_rewind(target, &spa, FTAG, policy,
9252 			    NULL);
9253 			if (error) {
9254 				/*
9255 				 * If we're missing the log device then
9256 				 * try opening the pool after clearing the
9257 				 * log state.
9258 				 */
9259 				mutex_enter(&spa_namespace_lock);
9260 				if ((spa = spa_lookup(target)) != NULL &&
9261 				    spa->spa_log_state == SPA_LOG_MISSING) {
9262 					spa->spa_log_state = SPA_LOG_CLEAR;
9263 					error = 0;
9264 				}
9265 				mutex_exit(&spa_namespace_lock);
9266 
9267 				if (!error) {
9268 					error = spa_open_rewind(target, &spa,
9269 					    FTAG, policy, NULL);
9270 				}
9271 			}
9272 		} else if (strpbrk(target, "#") != NULL) {
9273 			dsl_pool_t *dp;
9274 			error = dsl_pool_hold(target, FTAG, &dp);
9275 			if (error != 0) {
9276 				fatal("can't dump '%s': %s", target,
9277 				    strerror(error));
9278 			}
9279 			error = dump_bookmark(dp, target, B_TRUE, verbose > 1);
9280 			dsl_pool_rele(dp, FTAG);
9281 			if (error != 0) {
9282 				fatal("can't dump '%s': %s", target,
9283 				    strerror(error));
9284 			}
9285 			return (error);
9286 		} else {
9287 			target_pool = strdup(target);
9288 			if (strpbrk(target, "/@") != NULL)
9289 				*strpbrk(target_pool, "/@") = '\0';
9290 
9291 			zdb_set_skip_mmp(target);
9292 			/*
9293 			 * If -N was supplied, the user has indicated that
9294 			 * zdb -d <pool>/<objsetID> is in effect.  Otherwise
9295 			 * we first assume that the dataset string is the
9296 			 * dataset name.  If dmu_objset_hold fails with the
9297 			 * dataset string, and we have an objset_id, retry the
9298 			 * lookup with the objsetID.
9299 			 */
9300 			boolean_t retry = B_TRUE;
9301 retry_lookup:
9302 			if (dataset_lookup == B_TRUE) {
9303 				/*
9304 				 * Use the supplied id to get the name
9305 				 * for open_objset.
9306 				 */
9307 				error = spa_open(target_pool, &spa, FTAG);
9308 				if (error == 0) {
9309 					error = name_from_objset_id(spa,
9310 					    objset_id, dsname);
9311 					spa_close(spa, FTAG);
9312 					if (error == 0)
9313 						target = dsname;
9314 				}
9315 			}
9316 			if (error == 0) {
9317 				if (objset_id > 0 && retry) {
9318 					int err = dmu_objset_hold(target, FTAG,
9319 					    &os);
9320 					if (err) {
9321 						dataset_lookup = B_TRUE;
9322 						retry = B_FALSE;
9323 						goto retry_lookup;
9324 					} else {
9325 						dmu_objset_rele(os, FTAG);
9326 					}
9327 				}
9328 				error = open_objset(target, FTAG, &os);
9329 			}
9330 			if (error == 0)
9331 				spa = dmu_objset_spa(os);
9332 			free(target_pool);
9333 		}
9334 	}
9335 	nvlist_free(policy);
9336 
9337 	if (error)
9338 		fatal("can't open '%s': %s", target, strerror(error));
9339 
9340 	/*
9341 	 * Set the pool failure mode to panic in order to prevent the pool
9342 	 * from suspending.  A suspended I/O will have no way to resume and
9343 	 * can prevent the zdb(8) command from terminating as expected.
9344 	 */
9345 	if (spa != NULL)
9346 		spa->spa_failmode = ZIO_FAILURE_MODE_PANIC;
9347 
9348 	argv++;
9349 	argc--;
9350 	if (dump_opt['r']) {
9351 		error = zdb_copy_object(os, object, argv[1]);
9352 	} else if (!dump_opt['R']) {
9353 		flagbits['d'] = ZOR_FLAG_DIRECTORY;
9354 		flagbits['f'] = ZOR_FLAG_PLAIN_FILE;
9355 		flagbits['m'] = ZOR_FLAG_SPACE_MAP;
9356 		flagbits['z'] = ZOR_FLAG_ZAP;
9357 		flagbits['A'] = ZOR_FLAG_ALL_TYPES;
9358 
9359 		if (argc > 0 && dump_opt['d']) {
9360 			zopt_object_args = argc;
9361 			zopt_object_ranges = calloc(zopt_object_args,
9362 			    sizeof (zopt_object_range_t));
9363 			for (unsigned i = 0; i < zopt_object_args; i++) {
9364 				int err;
9365 				const char *msg = NULL;
9366 
9367 				err = parse_object_range(argv[i],
9368 				    &zopt_object_ranges[i], &msg);
9369 				if (err != 0)
9370 					fatal("Bad object or range: '%s': %s\n",
9371 					    argv[i], msg ?: "");
9372 			}
9373 		} else if (argc > 0 && dump_opt['m']) {
9374 			zopt_metaslab_args = argc;
9375 			zopt_metaslab = calloc(zopt_metaslab_args,
9376 			    sizeof (uint64_t));
9377 			for (unsigned i = 0; i < zopt_metaslab_args; i++) {
9378 				errno = 0;
9379 				zopt_metaslab[i] = strtoull(argv[i], NULL, 0);
9380 				if (zopt_metaslab[i] == 0 && errno != 0)
9381 					fatal("bad number %s: %s", argv[i],
9382 					    strerror(errno));
9383 			}
9384 		}
9385 		if (dump_opt['B']) {
9386 			dump_backup(target, objset_id,
9387 			    argc > 0 ? argv[0] : NULL);
9388 		} else if (os != NULL) {
9389 			dump_objset(os);
9390 		} else if (zopt_object_args > 0 && !dump_opt['m']) {
9391 			dump_objset(spa->spa_meta_objset);
9392 		} else {
9393 			dump_zpool(spa);
9394 		}
9395 	} else {
9396 		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
9397 		flagbits['c'] = ZDB_FLAG_CHECKSUM;
9398 		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
9399 		flagbits['e'] = ZDB_FLAG_BSWAP;
9400 		flagbits['g'] = ZDB_FLAG_GBH;
9401 		flagbits['i'] = ZDB_FLAG_INDIRECT;
9402 		flagbits['r'] = ZDB_FLAG_RAW;
9403 		flagbits['v'] = ZDB_FLAG_VERBOSE;
9404 
9405 		for (int i = 0; i < argc; i++)
9406 			zdb_read_block(argv[i], spa);
9407 	}
9408 
9409 	if (dump_opt['k']) {
9410 		free(checkpoint_pool);
9411 		if (!target_is_spa)
9412 			free(checkpoint_target);
9413 	}
9414 
9415 	if (os != NULL) {
9416 		close_objset(os, FTAG);
9417 	} else {
9418 		spa_close(spa, FTAG);
9419 	}
9420 
9421 	fuid_table_destroy();
9422 
9423 	dump_debug_buffer();
9424 
9425 	kernel_fini();
9426 
9427 	return (error);
9428 }
9429