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