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