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