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