xref: /freebsd/sys/contrib/openzfs/cmd/zdb/zdb.c (revision 1323ec571215a77ddd21294f0871979d5ad6b992)
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 = {{{0}}};
2039 	ddt_stat_t dds_total = {0};
2040 
2041 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
2042 		ddt_t *ddt = spa->spa_ddt[c];
2043 		for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
2044 			for (enum ddt_class class = 0; class < DDT_CLASSES;
2045 			    class++) {
2046 				dump_ddt(ddt, type, class);
2047 			}
2048 		}
2049 	}
2050 
2051 	ddt_get_dedup_stats(spa, &dds_total);
2052 
2053 	if (dds_total.dds_blocks == 0) {
2054 		(void) printf("All DDTs are empty\n");
2055 		return;
2056 	}
2057 
2058 	(void) printf("\n");
2059 
2060 	if (dump_opt['D'] > 1) {
2061 		(void) printf("DDT histogram (aggregated over all DDTs):\n");
2062 		ddt_get_dedup_histogram(spa, &ddh_total);
2063 		zpool_dump_ddt(&dds_total, &ddh_total);
2064 	}
2065 
2066 	dump_dedup_ratio(&dds_total);
2067 }
2068 
2069 static void
2070 dump_dtl_seg(void *arg, uint64_t start, uint64_t size)
2071 {
2072 	char *prefix = arg;
2073 
2074 	(void) printf("%s [%llu,%llu) length %llu\n",
2075 	    prefix,
2076 	    (u_longlong_t)start,
2077 	    (u_longlong_t)(start + size),
2078 	    (u_longlong_t)(size));
2079 }
2080 
2081 static void
2082 dump_dtl(vdev_t *vd, int indent)
2083 {
2084 	spa_t *spa = vd->vdev_spa;
2085 	boolean_t required;
2086 	const char *name[DTL_TYPES] = { "missing", "partial", "scrub",
2087 		"outage" };
2088 	char prefix[256];
2089 
2090 	spa_vdev_state_enter(spa, SCL_NONE);
2091 	required = vdev_dtl_required(vd);
2092 	(void) spa_vdev_state_exit(spa, NULL, 0);
2093 
2094 	if (indent == 0)
2095 		(void) printf("\nDirty time logs:\n\n");
2096 
2097 	(void) printf("\t%*s%s [%s]\n", indent, "",
2098 	    vd->vdev_path ? vd->vdev_path :
2099 	    vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
2100 	    required ? "DTL-required" : "DTL-expendable");
2101 
2102 	for (int t = 0; t < DTL_TYPES; t++) {
2103 		range_tree_t *rt = vd->vdev_dtl[t];
2104 		if (range_tree_space(rt) == 0)
2105 			continue;
2106 		(void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
2107 		    indent + 2, "", name[t]);
2108 		range_tree_walk(rt, dump_dtl_seg, prefix);
2109 		if (dump_opt['d'] > 5 && vd->vdev_children == 0)
2110 			dump_spacemap(spa->spa_meta_objset,
2111 			    vd->vdev_dtl_sm);
2112 	}
2113 
2114 	for (unsigned c = 0; c < vd->vdev_children; c++)
2115 		dump_dtl(vd->vdev_child[c], indent + 4);
2116 }
2117 
2118 static void
2119 dump_history(spa_t *spa)
2120 {
2121 	nvlist_t **events = NULL;
2122 	char *buf;
2123 	uint64_t resid, len, off = 0;
2124 	uint_t num = 0;
2125 	int error;
2126 	char tbuf[30];
2127 
2128 	if ((buf = malloc(SPA_OLD_MAXBLOCKSIZE)) == NULL) {
2129 		(void) fprintf(stderr, "%s: unable to allocate I/O buffer\n",
2130 		    __func__);
2131 		return;
2132 	}
2133 
2134 	do {
2135 		len = SPA_OLD_MAXBLOCKSIZE;
2136 
2137 		if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
2138 			(void) fprintf(stderr, "Unable to read history: "
2139 			    "error %d\n", error);
2140 			free(buf);
2141 			return;
2142 		}
2143 
2144 		if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
2145 			break;
2146 
2147 		off -= resid;
2148 	} while (len != 0);
2149 
2150 	(void) printf("\nHistory:\n");
2151 	for (unsigned i = 0; i < num; i++) {
2152 		boolean_t printed = B_FALSE;
2153 
2154 		if (nvlist_exists(events[i], ZPOOL_HIST_TIME)) {
2155 			time_t tsec;
2156 			struct tm t;
2157 
2158 			tsec = fnvlist_lookup_uint64(events[i],
2159 			    ZPOOL_HIST_TIME);
2160 			(void) localtime_r(&tsec, &t);
2161 			(void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
2162 		} else {
2163 			tbuf[0] = '\0';
2164 		}
2165 
2166 		if (nvlist_exists(events[i], ZPOOL_HIST_CMD)) {
2167 			(void) printf("%s %s\n", tbuf,
2168 			    fnvlist_lookup_string(events[i], ZPOOL_HIST_CMD));
2169 		} else if (nvlist_exists(events[i], ZPOOL_HIST_INT_EVENT)) {
2170 			uint64_t ievent;
2171 
2172 			ievent = fnvlist_lookup_uint64(events[i],
2173 			    ZPOOL_HIST_INT_EVENT);
2174 			if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
2175 				goto next;
2176 
2177 			(void) printf(" %s [internal %s txg:%ju] %s\n",
2178 			    tbuf,
2179 			    zfs_history_event_names[ievent],
2180 			    fnvlist_lookup_uint64(events[i],
2181 			    ZPOOL_HIST_TXG),
2182 			    fnvlist_lookup_string(events[i],
2183 			    ZPOOL_HIST_INT_STR));
2184 		} else if (nvlist_exists(events[i], ZPOOL_HIST_INT_NAME)) {
2185 			(void) printf("%s [txg:%ju] %s", tbuf,
2186 			    fnvlist_lookup_uint64(events[i],
2187 			    ZPOOL_HIST_TXG),
2188 			    fnvlist_lookup_string(events[i],
2189 			    ZPOOL_HIST_INT_NAME));
2190 
2191 			if (nvlist_exists(events[i], ZPOOL_HIST_DSNAME)) {
2192 				(void) printf(" %s (%llu)",
2193 				    fnvlist_lookup_string(events[i],
2194 				    ZPOOL_HIST_DSNAME),
2195 				    (u_longlong_t)fnvlist_lookup_uint64(
2196 				    events[i],
2197 				    ZPOOL_HIST_DSID));
2198 			}
2199 
2200 			(void) printf(" %s\n", fnvlist_lookup_string(events[i],
2201 			    ZPOOL_HIST_INT_STR));
2202 		} else if (nvlist_exists(events[i], ZPOOL_HIST_IOCTL)) {
2203 			(void) printf("%s ioctl %s\n", tbuf,
2204 			    fnvlist_lookup_string(events[i],
2205 			    ZPOOL_HIST_IOCTL));
2206 
2207 			if (nvlist_exists(events[i], ZPOOL_HIST_INPUT_NVL)) {
2208 				(void) printf("    input:\n");
2209 				dump_nvlist(fnvlist_lookup_nvlist(events[i],
2210 				    ZPOOL_HIST_INPUT_NVL), 8);
2211 			}
2212 			if (nvlist_exists(events[i], ZPOOL_HIST_OUTPUT_NVL)) {
2213 				(void) printf("    output:\n");
2214 				dump_nvlist(fnvlist_lookup_nvlist(events[i],
2215 				    ZPOOL_HIST_OUTPUT_NVL), 8);
2216 			}
2217 			if (nvlist_exists(events[i], ZPOOL_HIST_ERRNO)) {
2218 				(void) printf("    errno: %lld\n",
2219 				    (longlong_t)fnvlist_lookup_int64(events[i],
2220 				    ZPOOL_HIST_ERRNO));
2221 			}
2222 		} else {
2223 			goto next;
2224 		}
2225 
2226 		printed = B_TRUE;
2227 next:
2228 		if (dump_opt['h'] > 1) {
2229 			if (!printed)
2230 				(void) printf("unrecognized record:\n");
2231 			dump_nvlist(events[i], 2);
2232 		}
2233 	}
2234 	free(buf);
2235 }
2236 
2237 static void
2238 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
2239 {
2240 	(void) os, (void) object, (void) data, (void) size;
2241 }
2242 
2243 static uint64_t
2244 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp,
2245     const zbookmark_phys_t *zb)
2246 {
2247 	if (dnp == NULL) {
2248 		ASSERT(zb->zb_level < 0);
2249 		if (zb->zb_object == 0)
2250 			return (zb->zb_blkid);
2251 		return (zb->zb_blkid * BP_GET_LSIZE(bp));
2252 	}
2253 
2254 	ASSERT(zb->zb_level >= 0);
2255 
2256 	return ((zb->zb_blkid <<
2257 	    (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
2258 	    dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
2259 }
2260 
2261 static void
2262 snprintf_zstd_header(spa_t *spa, char *blkbuf, size_t buflen,
2263     const blkptr_t *bp)
2264 {
2265 	abd_t *pabd;
2266 	void *buf;
2267 	zio_t *zio;
2268 	zfs_zstdhdr_t zstd_hdr;
2269 	int error;
2270 
2271 	if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_ZSTD)
2272 		return;
2273 
2274 	if (BP_IS_HOLE(bp))
2275 		return;
2276 
2277 	if (BP_IS_EMBEDDED(bp)) {
2278 		buf = malloc(SPA_MAXBLOCKSIZE);
2279 		if (buf == NULL) {
2280 			(void) fprintf(stderr, "out of memory\n");
2281 			exit(1);
2282 		}
2283 		decode_embedded_bp_compressed(bp, buf);
2284 		memcpy(&zstd_hdr, buf, sizeof (zstd_hdr));
2285 		free(buf);
2286 		zstd_hdr.c_len = BE_32(zstd_hdr.c_len);
2287 		zstd_hdr.raw_version_level = BE_32(zstd_hdr.raw_version_level);
2288 		(void) snprintf(blkbuf + strlen(blkbuf),
2289 		    buflen - strlen(blkbuf),
2290 		    " ZSTD:size=%u:version=%u:level=%u:EMBEDDED",
2291 		    zstd_hdr.c_len, zfs_get_hdrversion(&zstd_hdr),
2292 		    zfs_get_hdrlevel(&zstd_hdr));
2293 		return;
2294 	}
2295 
2296 	pabd = abd_alloc_for_io(SPA_MAXBLOCKSIZE, B_FALSE);
2297 	zio = zio_root(spa, NULL, NULL, 0);
2298 
2299 	/* Decrypt but don't decompress so we can read the compression header */
2300 	zio_nowait(zio_read(zio, spa, bp, pabd, BP_GET_PSIZE(bp), NULL, NULL,
2301 	    ZIO_PRIORITY_SYNC_READ, ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW_COMPRESS,
2302 	    NULL));
2303 	error = zio_wait(zio);
2304 	if (error) {
2305 		(void) fprintf(stderr, "read failed: %d\n", error);
2306 		return;
2307 	}
2308 	buf = abd_borrow_buf_copy(pabd, BP_GET_LSIZE(bp));
2309 	memcpy(&zstd_hdr, buf, sizeof (zstd_hdr));
2310 	zstd_hdr.c_len = BE_32(zstd_hdr.c_len);
2311 	zstd_hdr.raw_version_level = BE_32(zstd_hdr.raw_version_level);
2312 
2313 	(void) snprintf(blkbuf + strlen(blkbuf),
2314 	    buflen - strlen(blkbuf),
2315 	    " ZSTD:size=%u:version=%u:level=%u:NORMAL",
2316 	    zstd_hdr.c_len, zfs_get_hdrversion(&zstd_hdr),
2317 	    zfs_get_hdrlevel(&zstd_hdr));
2318 
2319 	abd_return_buf_copy(pabd, buf, BP_GET_LSIZE(bp));
2320 }
2321 
2322 static void
2323 snprintf_blkptr_compact(char *blkbuf, size_t buflen, const blkptr_t *bp,
2324     boolean_t bp_freed)
2325 {
2326 	const dva_t *dva = bp->blk_dva;
2327 	int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
2328 	int i;
2329 
2330 	if (dump_opt['b'] >= 6) {
2331 		snprintf_blkptr(blkbuf, buflen, bp);
2332 		if (bp_freed) {
2333 			(void) snprintf(blkbuf + strlen(blkbuf),
2334 			    buflen - strlen(blkbuf), " %s", "FREE");
2335 		}
2336 		return;
2337 	}
2338 
2339 	if (BP_IS_EMBEDDED(bp)) {
2340 		(void) sprintf(blkbuf,
2341 		    "EMBEDDED et=%u %llxL/%llxP B=%llu",
2342 		    (int)BPE_GET_ETYPE(bp),
2343 		    (u_longlong_t)BPE_GET_LSIZE(bp),
2344 		    (u_longlong_t)BPE_GET_PSIZE(bp),
2345 		    (u_longlong_t)bp->blk_birth);
2346 		return;
2347 	}
2348 
2349 	blkbuf[0] = '\0';
2350 
2351 	for (i = 0; i < ndvas; i++)
2352 		(void) snprintf(blkbuf + strlen(blkbuf),
2353 		    buflen - strlen(blkbuf), "%llu:%llx:%llx ",
2354 		    (u_longlong_t)DVA_GET_VDEV(&dva[i]),
2355 		    (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
2356 		    (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
2357 
2358 	if (BP_IS_HOLE(bp)) {
2359 		(void) snprintf(blkbuf + strlen(blkbuf),
2360 		    buflen - strlen(blkbuf),
2361 		    "%llxL B=%llu",
2362 		    (u_longlong_t)BP_GET_LSIZE(bp),
2363 		    (u_longlong_t)bp->blk_birth);
2364 	} else {
2365 		(void) snprintf(blkbuf + strlen(blkbuf),
2366 		    buflen - strlen(blkbuf),
2367 		    "%llxL/%llxP F=%llu B=%llu/%llu",
2368 		    (u_longlong_t)BP_GET_LSIZE(bp),
2369 		    (u_longlong_t)BP_GET_PSIZE(bp),
2370 		    (u_longlong_t)BP_GET_FILL(bp),
2371 		    (u_longlong_t)bp->blk_birth,
2372 		    (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
2373 		if (bp_freed)
2374 			(void) snprintf(blkbuf + strlen(blkbuf),
2375 			    buflen - strlen(blkbuf), " %s", "FREE");
2376 		(void) snprintf(blkbuf + strlen(blkbuf),
2377 		    buflen - strlen(blkbuf), " cksum=%llx:%llx:%llx:%llx",
2378 		    (u_longlong_t)bp->blk_cksum.zc_word[0],
2379 		    (u_longlong_t)bp->blk_cksum.zc_word[1],
2380 		    (u_longlong_t)bp->blk_cksum.zc_word[2],
2381 		    (u_longlong_t)bp->blk_cksum.zc_word[3]);
2382 	}
2383 }
2384 
2385 static void
2386 print_indirect(spa_t *spa, blkptr_t *bp, const zbookmark_phys_t *zb,
2387     const dnode_phys_t *dnp)
2388 {
2389 	char blkbuf[BP_SPRINTF_LEN];
2390 	int l;
2391 
2392 	if (!BP_IS_EMBEDDED(bp)) {
2393 		ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
2394 		ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
2395 	}
2396 
2397 	(void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
2398 
2399 	ASSERT(zb->zb_level >= 0);
2400 
2401 	for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
2402 		if (l == zb->zb_level) {
2403 			(void) printf("L%llx", (u_longlong_t)zb->zb_level);
2404 		} else {
2405 			(void) printf(" ");
2406 		}
2407 	}
2408 
2409 	snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp, B_FALSE);
2410 	if (dump_opt['Z'] && BP_GET_COMPRESS(bp) == ZIO_COMPRESS_ZSTD)
2411 		snprintf_zstd_header(spa, blkbuf, sizeof (blkbuf), bp);
2412 	(void) printf("%s\n", blkbuf);
2413 }
2414 
2415 static int
2416 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
2417     blkptr_t *bp, const zbookmark_phys_t *zb)
2418 {
2419 	int err = 0;
2420 
2421 	if (bp->blk_birth == 0)
2422 		return (0);
2423 
2424 	print_indirect(spa, bp, zb, dnp);
2425 
2426 	if (BP_GET_LEVEL(bp) > 0 && !BP_IS_HOLE(bp)) {
2427 		arc_flags_t flags = ARC_FLAG_WAIT;
2428 		int i;
2429 		blkptr_t *cbp;
2430 		int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
2431 		arc_buf_t *buf;
2432 		uint64_t fill = 0;
2433 		ASSERT(!BP_IS_REDACTED(bp));
2434 
2435 		err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
2436 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
2437 		if (err)
2438 			return (err);
2439 		ASSERT(buf->b_data);
2440 
2441 		/* recursively visit blocks below this */
2442 		cbp = buf->b_data;
2443 		for (i = 0; i < epb; i++, cbp++) {
2444 			zbookmark_phys_t czb;
2445 
2446 			SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
2447 			    zb->zb_level - 1,
2448 			    zb->zb_blkid * epb + i);
2449 			err = visit_indirect(spa, dnp, cbp, &czb);
2450 			if (err)
2451 				break;
2452 			fill += BP_GET_FILL(cbp);
2453 		}
2454 		if (!err)
2455 			ASSERT3U(fill, ==, BP_GET_FILL(bp));
2456 		arc_buf_destroy(buf, &buf);
2457 	}
2458 
2459 	return (err);
2460 }
2461 
2462 static void
2463 dump_indirect(dnode_t *dn)
2464 {
2465 	dnode_phys_t *dnp = dn->dn_phys;
2466 	zbookmark_phys_t czb;
2467 
2468 	(void) printf("Indirect blocks:\n");
2469 
2470 	SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
2471 	    dn->dn_object, dnp->dn_nlevels - 1, 0);
2472 	for (int j = 0; j < dnp->dn_nblkptr; j++) {
2473 		czb.zb_blkid = j;
2474 		(void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
2475 		    &dnp->dn_blkptr[j], &czb);
2476 	}
2477 
2478 	(void) printf("\n");
2479 }
2480 
2481 static void
2482 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
2483 {
2484 	(void) os, (void) object;
2485 	dsl_dir_phys_t *dd = data;
2486 	time_t crtime;
2487 	char nice[32];
2488 
2489 	/* make sure nicenum has enough space */
2490 	_Static_assert(sizeof (nice) >= NN_NUMBUF_SZ, "nice truncated");
2491 
2492 	if (dd == NULL)
2493 		return;
2494 
2495 	ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
2496 
2497 	crtime = dd->dd_creation_time;
2498 	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
2499 	(void) printf("\t\thead_dataset_obj = %llu\n",
2500 	    (u_longlong_t)dd->dd_head_dataset_obj);
2501 	(void) printf("\t\tparent_dir_obj = %llu\n",
2502 	    (u_longlong_t)dd->dd_parent_obj);
2503 	(void) printf("\t\torigin_obj = %llu\n",
2504 	    (u_longlong_t)dd->dd_origin_obj);
2505 	(void) printf("\t\tchild_dir_zapobj = %llu\n",
2506 	    (u_longlong_t)dd->dd_child_dir_zapobj);
2507 	zdb_nicenum(dd->dd_used_bytes, nice, sizeof (nice));
2508 	(void) printf("\t\tused_bytes = %s\n", nice);
2509 	zdb_nicenum(dd->dd_compressed_bytes, nice, sizeof (nice));
2510 	(void) printf("\t\tcompressed_bytes = %s\n", nice);
2511 	zdb_nicenum(dd->dd_uncompressed_bytes, nice, sizeof (nice));
2512 	(void) printf("\t\tuncompressed_bytes = %s\n", nice);
2513 	zdb_nicenum(dd->dd_quota, nice, sizeof (nice));
2514 	(void) printf("\t\tquota = %s\n", nice);
2515 	zdb_nicenum(dd->dd_reserved, nice, sizeof (nice));
2516 	(void) printf("\t\treserved = %s\n", nice);
2517 	(void) printf("\t\tprops_zapobj = %llu\n",
2518 	    (u_longlong_t)dd->dd_props_zapobj);
2519 	(void) printf("\t\tdeleg_zapobj = %llu\n",
2520 	    (u_longlong_t)dd->dd_deleg_zapobj);
2521 	(void) printf("\t\tflags = %llx\n",
2522 	    (u_longlong_t)dd->dd_flags);
2523 
2524 #define	DO(which) \
2525 	zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice, \
2526 	    sizeof (nice)); \
2527 	(void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
2528 	DO(HEAD);
2529 	DO(SNAP);
2530 	DO(CHILD);
2531 	DO(CHILD_RSRV);
2532 	DO(REFRSRV);
2533 #undef DO
2534 	(void) printf("\t\tclones = %llu\n",
2535 	    (u_longlong_t)dd->dd_clones);
2536 }
2537 
2538 static void
2539 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
2540 {
2541 	(void) os, (void) object;
2542 	dsl_dataset_phys_t *ds = data;
2543 	time_t crtime;
2544 	char used[32], compressed[32], uncompressed[32], unique[32];
2545 	char blkbuf[BP_SPRINTF_LEN];
2546 
2547 	/* make sure nicenum has enough space */
2548 	_Static_assert(sizeof (used) >= NN_NUMBUF_SZ, "used truncated");
2549 	_Static_assert(sizeof (compressed) >= NN_NUMBUF_SZ,
2550 	    "compressed truncated");
2551 	_Static_assert(sizeof (uncompressed) >= NN_NUMBUF_SZ,
2552 	    "uncompressed truncated");
2553 	_Static_assert(sizeof (unique) >= NN_NUMBUF_SZ, "unique truncated");
2554 
2555 	if (ds == NULL)
2556 		return;
2557 
2558 	ASSERT(size == sizeof (*ds));
2559 	crtime = ds->ds_creation_time;
2560 	zdb_nicenum(ds->ds_referenced_bytes, used, sizeof (used));
2561 	zdb_nicenum(ds->ds_compressed_bytes, compressed, sizeof (compressed));
2562 	zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed,
2563 	    sizeof (uncompressed));
2564 	zdb_nicenum(ds->ds_unique_bytes, unique, sizeof (unique));
2565 	snprintf_blkptr(blkbuf, sizeof (blkbuf), &ds->ds_bp);
2566 
2567 	(void) printf("\t\tdir_obj = %llu\n",
2568 	    (u_longlong_t)ds->ds_dir_obj);
2569 	(void) printf("\t\tprev_snap_obj = %llu\n",
2570 	    (u_longlong_t)ds->ds_prev_snap_obj);
2571 	(void) printf("\t\tprev_snap_txg = %llu\n",
2572 	    (u_longlong_t)ds->ds_prev_snap_txg);
2573 	(void) printf("\t\tnext_snap_obj = %llu\n",
2574 	    (u_longlong_t)ds->ds_next_snap_obj);
2575 	(void) printf("\t\tsnapnames_zapobj = %llu\n",
2576 	    (u_longlong_t)ds->ds_snapnames_zapobj);
2577 	(void) printf("\t\tnum_children = %llu\n",
2578 	    (u_longlong_t)ds->ds_num_children);
2579 	(void) printf("\t\tuserrefs_obj = %llu\n",
2580 	    (u_longlong_t)ds->ds_userrefs_obj);
2581 	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
2582 	(void) printf("\t\tcreation_txg = %llu\n",
2583 	    (u_longlong_t)ds->ds_creation_txg);
2584 	(void) printf("\t\tdeadlist_obj = %llu\n",
2585 	    (u_longlong_t)ds->ds_deadlist_obj);
2586 	(void) printf("\t\tused_bytes = %s\n", used);
2587 	(void) printf("\t\tcompressed_bytes = %s\n", compressed);
2588 	(void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
2589 	(void) printf("\t\tunique = %s\n", unique);
2590 	(void) printf("\t\tfsid_guid = %llu\n",
2591 	    (u_longlong_t)ds->ds_fsid_guid);
2592 	(void) printf("\t\tguid = %llu\n",
2593 	    (u_longlong_t)ds->ds_guid);
2594 	(void) printf("\t\tflags = %llx\n",
2595 	    (u_longlong_t)ds->ds_flags);
2596 	(void) printf("\t\tnext_clones_obj = %llu\n",
2597 	    (u_longlong_t)ds->ds_next_clones_obj);
2598 	(void) printf("\t\tprops_obj = %llu\n",
2599 	    (u_longlong_t)ds->ds_props_obj);
2600 	(void) printf("\t\tbp = %s\n", blkbuf);
2601 }
2602 
2603 static int
2604 dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2605 {
2606 	(void) arg, (void) tx;
2607 	char blkbuf[BP_SPRINTF_LEN];
2608 
2609 	if (bp->blk_birth != 0) {
2610 		snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
2611 		(void) printf("\t%s\n", blkbuf);
2612 	}
2613 	return (0);
2614 }
2615 
2616 static void
2617 dump_bptree(objset_t *os, uint64_t obj, const char *name)
2618 {
2619 	char bytes[32];
2620 	bptree_phys_t *bt;
2621 	dmu_buf_t *db;
2622 
2623 	/* make sure nicenum has enough space */
2624 	_Static_assert(sizeof (bytes) >= NN_NUMBUF_SZ, "bytes truncated");
2625 
2626 	if (dump_opt['d'] < 3)
2627 		return;
2628 
2629 	VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
2630 	bt = db->db_data;
2631 	zdb_nicenum(bt->bt_bytes, bytes, sizeof (bytes));
2632 	(void) printf("\n    %s: %llu datasets, %s\n",
2633 	    name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
2634 	dmu_buf_rele(db, FTAG);
2635 
2636 	if (dump_opt['d'] < 5)
2637 		return;
2638 
2639 	(void) printf("\n");
2640 
2641 	(void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
2642 }
2643 
2644 static int
2645 dump_bpobj_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed, dmu_tx_t *tx)
2646 {
2647 	(void) arg, (void) tx;
2648 	char blkbuf[BP_SPRINTF_LEN];
2649 
2650 	ASSERT(bp->blk_birth != 0);
2651 	snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp, bp_freed);
2652 	(void) printf("\t%s\n", blkbuf);
2653 	return (0);
2654 }
2655 
2656 static void
2657 dump_full_bpobj(bpobj_t *bpo, const char *name, int indent)
2658 {
2659 	char bytes[32];
2660 	char comp[32];
2661 	char uncomp[32];
2662 	uint64_t i;
2663 
2664 	/* make sure nicenum has enough space */
2665 	_Static_assert(sizeof (bytes) >= NN_NUMBUF_SZ, "bytes truncated");
2666 	_Static_assert(sizeof (comp) >= NN_NUMBUF_SZ, "comp truncated");
2667 	_Static_assert(sizeof (uncomp) >= NN_NUMBUF_SZ, "uncomp truncated");
2668 
2669 	if (dump_opt['d'] < 3)
2670 		return;
2671 
2672 	zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes, sizeof (bytes));
2673 	if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
2674 		zdb_nicenum(bpo->bpo_phys->bpo_comp, comp, sizeof (comp));
2675 		zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp, sizeof (uncomp));
2676 		if (bpo->bpo_havefreed) {
2677 			(void) printf("    %*s: object %llu, %llu local "
2678 			    "blkptrs, %llu freed, %llu subobjs in object %llu, "
2679 			    "%s (%s/%s comp)\n",
2680 			    indent * 8, name,
2681 			    (u_longlong_t)bpo->bpo_object,
2682 			    (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2683 			    (u_longlong_t)bpo->bpo_phys->bpo_num_freed,
2684 			    (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
2685 			    (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
2686 			    bytes, comp, uncomp);
2687 		} else {
2688 			(void) printf("    %*s: object %llu, %llu local "
2689 			    "blkptrs, %llu subobjs in object %llu, "
2690 			    "%s (%s/%s comp)\n",
2691 			    indent * 8, name,
2692 			    (u_longlong_t)bpo->bpo_object,
2693 			    (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2694 			    (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
2695 			    (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
2696 			    bytes, comp, uncomp);
2697 		}
2698 
2699 		for (i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
2700 			uint64_t subobj;
2701 			bpobj_t subbpo;
2702 			int error;
2703 			VERIFY0(dmu_read(bpo->bpo_os,
2704 			    bpo->bpo_phys->bpo_subobjs,
2705 			    i * sizeof (subobj), sizeof (subobj), &subobj, 0));
2706 			error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
2707 			if (error != 0) {
2708 				(void) printf("ERROR %u while trying to open "
2709 				    "subobj id %llu\n",
2710 				    error, (u_longlong_t)subobj);
2711 				continue;
2712 			}
2713 			dump_full_bpobj(&subbpo, "subobj", indent + 1);
2714 			bpobj_close(&subbpo);
2715 		}
2716 	} else {
2717 		if (bpo->bpo_havefreed) {
2718 			(void) printf("    %*s: object %llu, %llu blkptrs, "
2719 			    "%llu freed, %s\n",
2720 			    indent * 8, name,
2721 			    (u_longlong_t)bpo->bpo_object,
2722 			    (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2723 			    (u_longlong_t)bpo->bpo_phys->bpo_num_freed,
2724 			    bytes);
2725 		} else {
2726 			(void) printf("    %*s: object %llu, %llu blkptrs, "
2727 			    "%s\n",
2728 			    indent * 8, name,
2729 			    (u_longlong_t)bpo->bpo_object,
2730 			    (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
2731 			    bytes);
2732 		}
2733 	}
2734 
2735 	if (dump_opt['d'] < 5)
2736 		return;
2737 
2738 
2739 	if (indent == 0) {
2740 		(void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
2741 		(void) printf("\n");
2742 	}
2743 }
2744 
2745 static int
2746 dump_bookmark(dsl_pool_t *dp, char *name, boolean_t print_redact,
2747     boolean_t print_list)
2748 {
2749 	int err = 0;
2750 	zfs_bookmark_phys_t prop;
2751 	objset_t *mos = dp->dp_spa->spa_meta_objset;
2752 	err = dsl_bookmark_lookup(dp, name, NULL, &prop);
2753 
2754 	if (err != 0) {
2755 		return (err);
2756 	}
2757 
2758 	(void) printf("\t#%s: ", strchr(name, '#') + 1);
2759 	(void) printf("{guid: %llx creation_txg: %llu creation_time: "
2760 	    "%llu redaction_obj: %llu}\n", (u_longlong_t)prop.zbm_guid,
2761 	    (u_longlong_t)prop.zbm_creation_txg,
2762 	    (u_longlong_t)prop.zbm_creation_time,
2763 	    (u_longlong_t)prop.zbm_redaction_obj);
2764 
2765 	IMPLY(print_list, print_redact);
2766 	if (!print_redact || prop.zbm_redaction_obj == 0)
2767 		return (0);
2768 
2769 	redaction_list_t *rl;
2770 	VERIFY0(dsl_redaction_list_hold_obj(dp,
2771 	    prop.zbm_redaction_obj, FTAG, &rl));
2772 
2773 	redaction_list_phys_t *rlp = rl->rl_phys;
2774 	(void) printf("\tRedacted:\n\t\tProgress: ");
2775 	if (rlp->rlp_last_object != UINT64_MAX ||
2776 	    rlp->rlp_last_blkid != UINT64_MAX) {
2777 		(void) printf("%llu %llu (incomplete)\n",
2778 		    (u_longlong_t)rlp->rlp_last_object,
2779 		    (u_longlong_t)rlp->rlp_last_blkid);
2780 	} else {
2781 		(void) printf("complete\n");
2782 	}
2783 	(void) printf("\t\tSnapshots: [");
2784 	for (unsigned int i = 0; i < rlp->rlp_num_snaps; i++) {
2785 		if (i > 0)
2786 			(void) printf(", ");
2787 		(void) printf("%0llu",
2788 		    (u_longlong_t)rlp->rlp_snaps[i]);
2789 	}
2790 	(void) printf("]\n\t\tLength: %llu\n",
2791 	    (u_longlong_t)rlp->rlp_num_entries);
2792 
2793 	if (!print_list) {
2794 		dsl_redaction_list_rele(rl, FTAG);
2795 		return (0);
2796 	}
2797 
2798 	if (rlp->rlp_num_entries == 0) {
2799 		dsl_redaction_list_rele(rl, FTAG);
2800 		(void) printf("\t\tRedaction List: []\n\n");
2801 		return (0);
2802 	}
2803 
2804 	redact_block_phys_t *rbp_buf;
2805 	uint64_t size;
2806 	dmu_object_info_t doi;
2807 
2808 	VERIFY0(dmu_object_info(mos, prop.zbm_redaction_obj, &doi));
2809 	size = doi.doi_max_offset;
2810 	rbp_buf = kmem_alloc(size, KM_SLEEP);
2811 
2812 	err = dmu_read(mos, prop.zbm_redaction_obj, 0, size,
2813 	    rbp_buf, 0);
2814 	if (err != 0) {
2815 		dsl_redaction_list_rele(rl, FTAG);
2816 		kmem_free(rbp_buf, size);
2817 		return (err);
2818 	}
2819 
2820 	(void) printf("\t\tRedaction List: [{object: %llx, offset: "
2821 	    "%llx, blksz: %x, count: %llx}",
2822 	    (u_longlong_t)rbp_buf[0].rbp_object,
2823 	    (u_longlong_t)rbp_buf[0].rbp_blkid,
2824 	    (uint_t)(redact_block_get_size(&rbp_buf[0])),
2825 	    (u_longlong_t)redact_block_get_count(&rbp_buf[0]));
2826 
2827 	for (size_t i = 1; i < rlp->rlp_num_entries; i++) {
2828 		(void) printf(",\n\t\t{object: %llx, offset: %llx, "
2829 		    "blksz: %x, count: %llx}",
2830 		    (u_longlong_t)rbp_buf[i].rbp_object,
2831 		    (u_longlong_t)rbp_buf[i].rbp_blkid,
2832 		    (uint_t)(redact_block_get_size(&rbp_buf[i])),
2833 		    (u_longlong_t)redact_block_get_count(&rbp_buf[i]));
2834 	}
2835 	dsl_redaction_list_rele(rl, FTAG);
2836 	kmem_free(rbp_buf, size);
2837 	(void) printf("]\n\n");
2838 	return (0);
2839 }
2840 
2841 static void
2842 dump_bookmarks(objset_t *os, int verbosity)
2843 {
2844 	zap_cursor_t zc;
2845 	zap_attribute_t attr;
2846 	dsl_dataset_t *ds = dmu_objset_ds(os);
2847 	dsl_pool_t *dp = spa_get_dsl(os->os_spa);
2848 	objset_t *mos = os->os_spa->spa_meta_objset;
2849 	if (verbosity < 4)
2850 		return;
2851 	dsl_pool_config_enter(dp, FTAG);
2852 
2853 	for (zap_cursor_init(&zc, mos, ds->ds_bookmarks_obj);
2854 	    zap_cursor_retrieve(&zc, &attr) == 0;
2855 	    zap_cursor_advance(&zc)) {
2856 		char osname[ZFS_MAX_DATASET_NAME_LEN];
2857 		char buf[ZFS_MAX_DATASET_NAME_LEN];
2858 		dmu_objset_name(os, osname);
2859 		VERIFY3S(0, <=, snprintf(buf, sizeof (buf), "%s#%s", osname,
2860 		    attr.za_name));
2861 		(void) dump_bookmark(dp, buf, verbosity >= 5, verbosity >= 6);
2862 	}
2863 	zap_cursor_fini(&zc);
2864 	dsl_pool_config_exit(dp, FTAG);
2865 }
2866 
2867 static void
2868 bpobj_count_refd(bpobj_t *bpo)
2869 {
2870 	mos_obj_refd(bpo->bpo_object);
2871 
2872 	if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
2873 		mos_obj_refd(bpo->bpo_phys->bpo_subobjs);
2874 		for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
2875 			uint64_t subobj;
2876 			bpobj_t subbpo;
2877 			int error;
2878 			VERIFY0(dmu_read(bpo->bpo_os,
2879 			    bpo->bpo_phys->bpo_subobjs,
2880 			    i * sizeof (subobj), sizeof (subobj), &subobj, 0));
2881 			error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
2882 			if (error != 0) {
2883 				(void) printf("ERROR %u while trying to open "
2884 				    "subobj id %llu\n",
2885 				    error, (u_longlong_t)subobj);
2886 				continue;
2887 			}
2888 			bpobj_count_refd(&subbpo);
2889 			bpobj_close(&subbpo);
2890 		}
2891 	}
2892 }
2893 
2894 static int
2895 dsl_deadlist_entry_count_refd(void *arg, dsl_deadlist_entry_t *dle)
2896 {
2897 	spa_t *spa = arg;
2898 	uint64_t empty_bpobj = spa->spa_dsl_pool->dp_empty_bpobj;
2899 	if (dle->dle_bpobj.bpo_object != empty_bpobj)
2900 		bpobj_count_refd(&dle->dle_bpobj);
2901 	return (0);
2902 }
2903 
2904 static int
2905 dsl_deadlist_entry_dump(void *arg, dsl_deadlist_entry_t *dle)
2906 {
2907 	ASSERT(arg == NULL);
2908 	if (dump_opt['d'] >= 5) {
2909 		char buf[128];
2910 		(void) snprintf(buf, sizeof (buf),
2911 		    "mintxg %llu -> obj %llu",
2912 		    (longlong_t)dle->dle_mintxg,
2913 		    (longlong_t)dle->dle_bpobj.bpo_object);
2914 
2915 		dump_full_bpobj(&dle->dle_bpobj, buf, 0);
2916 	} else {
2917 		(void) printf("mintxg %llu -> obj %llu\n",
2918 		    (longlong_t)dle->dle_mintxg,
2919 		    (longlong_t)dle->dle_bpobj.bpo_object);
2920 	}
2921 	return (0);
2922 }
2923 
2924 static void
2925 dump_blkptr_list(dsl_deadlist_t *dl, char *name)
2926 {
2927 	char bytes[32];
2928 	char comp[32];
2929 	char uncomp[32];
2930 	char entries[32];
2931 	spa_t *spa = dmu_objset_spa(dl->dl_os);
2932 	uint64_t empty_bpobj = spa->spa_dsl_pool->dp_empty_bpobj;
2933 
2934 	if (dl->dl_oldfmt) {
2935 		if (dl->dl_bpobj.bpo_object != empty_bpobj)
2936 			bpobj_count_refd(&dl->dl_bpobj);
2937 	} else {
2938 		mos_obj_refd(dl->dl_object);
2939 		dsl_deadlist_iterate(dl, dsl_deadlist_entry_count_refd, spa);
2940 	}
2941 
2942 	/* make sure nicenum has enough space */
2943 	_Static_assert(sizeof (bytes) >= NN_NUMBUF_SZ, "bytes truncated");
2944 	_Static_assert(sizeof (comp) >= NN_NUMBUF_SZ, "comp truncated");
2945 	_Static_assert(sizeof (uncomp) >= NN_NUMBUF_SZ, "uncomp truncated");
2946 	_Static_assert(sizeof (entries) >= NN_NUMBUF_SZ, "entries truncated");
2947 
2948 	if (dump_opt['d'] < 3)
2949 		return;
2950 
2951 	if (dl->dl_oldfmt) {
2952 		dump_full_bpobj(&dl->dl_bpobj, "old-format deadlist", 0);
2953 		return;
2954 	}
2955 
2956 	zdb_nicenum(dl->dl_phys->dl_used, bytes, sizeof (bytes));
2957 	zdb_nicenum(dl->dl_phys->dl_comp, comp, sizeof (comp));
2958 	zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp, sizeof (uncomp));
2959 	zdb_nicenum(avl_numnodes(&dl->dl_tree), entries, sizeof (entries));
2960 	(void) printf("\n    %s: %s (%s/%s comp), %s entries\n",
2961 	    name, bytes, comp, uncomp, entries);
2962 
2963 	if (dump_opt['d'] < 4)
2964 		return;
2965 
2966 	(void) printf("\n");
2967 
2968 	dsl_deadlist_iterate(dl, dsl_deadlist_entry_dump, NULL);
2969 }
2970 
2971 static int
2972 verify_dd_livelist(objset_t *os)
2973 {
2974 	uint64_t ll_used, used, ll_comp, comp, ll_uncomp, uncomp;
2975 	dsl_pool_t *dp = spa_get_dsl(os->os_spa);
2976 	dsl_dir_t  *dd = os->os_dsl_dataset->ds_dir;
2977 
2978 	ASSERT(!dmu_objset_is_snapshot(os));
2979 	if (!dsl_deadlist_is_open(&dd->dd_livelist))
2980 		return (0);
2981 
2982 	/* Iterate through the livelist to check for duplicates */
2983 	dsl_deadlist_iterate(&dd->dd_livelist, sublivelist_verify_lightweight,
2984 	    NULL);
2985 
2986 	dsl_pool_config_enter(dp, FTAG);
2987 	dsl_deadlist_space(&dd->dd_livelist, &ll_used,
2988 	    &ll_comp, &ll_uncomp);
2989 
2990 	dsl_dataset_t *origin_ds;
2991 	ASSERT(dsl_pool_config_held(dp));
2992 	VERIFY0(dsl_dataset_hold_obj(dp,
2993 	    dsl_dir_phys(dd)->dd_origin_obj, FTAG, &origin_ds));
2994 	VERIFY0(dsl_dataset_space_written(origin_ds, os->os_dsl_dataset,
2995 	    &used, &comp, &uncomp));
2996 	dsl_dataset_rele(origin_ds, FTAG);
2997 	dsl_pool_config_exit(dp, FTAG);
2998 	/*
2999 	 *  It's possible that the dataset's uncomp space is larger than the
3000 	 *  livelist's because livelists do not track embedded block pointers
3001 	 */
3002 	if (used != ll_used || comp != ll_comp || uncomp < ll_uncomp) {
3003 		char nice_used[32], nice_comp[32], nice_uncomp[32];
3004 		(void) printf("Discrepancy in space accounting:\n");
3005 		zdb_nicenum(used, nice_used, sizeof (nice_used));
3006 		zdb_nicenum(comp, nice_comp, sizeof (nice_comp));
3007 		zdb_nicenum(uncomp, nice_uncomp, sizeof (nice_uncomp));
3008 		(void) printf("dir: used %s, comp %s, uncomp %s\n",
3009 		    nice_used, nice_comp, nice_uncomp);
3010 		zdb_nicenum(ll_used, nice_used, sizeof (nice_used));
3011 		zdb_nicenum(ll_comp, nice_comp, sizeof (nice_comp));
3012 		zdb_nicenum(ll_uncomp, nice_uncomp, sizeof (nice_uncomp));
3013 		(void) printf("livelist: used %s, comp %s, uncomp %s\n",
3014 		    nice_used, nice_comp, nice_uncomp);
3015 		return (1);
3016 	}
3017 	return (0);
3018 }
3019 
3020 static avl_tree_t idx_tree;
3021 static avl_tree_t domain_tree;
3022 static boolean_t fuid_table_loaded;
3023 static objset_t *sa_os = NULL;
3024 static sa_attr_type_t *sa_attr_table = NULL;
3025 
3026 static int
3027 open_objset(const char *path, void *tag, objset_t **osp)
3028 {
3029 	int err;
3030 	uint64_t sa_attrs = 0;
3031 	uint64_t version = 0;
3032 
3033 	VERIFY3P(sa_os, ==, NULL);
3034 	/*
3035 	 * We can't own an objset if it's redacted.  Therefore, we do this
3036 	 * dance: hold the objset, then acquire a long hold on its dataset, then
3037 	 * release the pool (which is held as part of holding the objset).
3038 	 */
3039 	err = dmu_objset_hold(path, tag, osp);
3040 	if (err != 0) {
3041 		(void) fprintf(stderr, "failed to hold dataset '%s': %s\n",
3042 		    path, strerror(err));
3043 		return (err);
3044 	}
3045 	dsl_dataset_long_hold(dmu_objset_ds(*osp), tag);
3046 	dsl_pool_rele(dmu_objset_pool(*osp), tag);
3047 
3048 	if (dmu_objset_type(*osp) == DMU_OST_ZFS && !(*osp)->os_encrypted) {
3049 		(void) zap_lookup(*osp, MASTER_NODE_OBJ, ZPL_VERSION_STR,
3050 		    8, 1, &version);
3051 		if (version >= ZPL_VERSION_SA) {
3052 			(void) zap_lookup(*osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
3053 			    8, 1, &sa_attrs);
3054 		}
3055 		err = sa_setup(*osp, sa_attrs, zfs_attr_table, ZPL_END,
3056 		    &sa_attr_table);
3057 		if (err != 0) {
3058 			(void) fprintf(stderr, "sa_setup failed: %s\n",
3059 			    strerror(err));
3060 			dsl_dataset_long_rele(dmu_objset_ds(*osp), tag);
3061 			dsl_dataset_rele(dmu_objset_ds(*osp), tag);
3062 			*osp = NULL;
3063 		}
3064 	}
3065 	sa_os = *osp;
3066 
3067 	return (0);
3068 }
3069 
3070 static void
3071 close_objset(objset_t *os, void *tag)
3072 {
3073 	VERIFY3P(os, ==, sa_os);
3074 	if (os->os_sa != NULL)
3075 		sa_tear_down(os);
3076 	dsl_dataset_long_rele(dmu_objset_ds(os), tag);
3077 	dsl_dataset_rele(dmu_objset_ds(os), tag);
3078 	sa_attr_table = NULL;
3079 	sa_os = NULL;
3080 }
3081 
3082 static void
3083 fuid_table_destroy(void)
3084 {
3085 	if (fuid_table_loaded) {
3086 		zfs_fuid_table_destroy(&idx_tree, &domain_tree);
3087 		fuid_table_loaded = B_FALSE;
3088 	}
3089 }
3090 
3091 /*
3092  * print uid or gid information.
3093  * For normal POSIX id just the id is printed in decimal format.
3094  * For CIFS files with FUID the fuid is printed in hex followed by
3095  * the domain-rid string.
3096  */
3097 static void
3098 print_idstr(uint64_t id, const char *id_type)
3099 {
3100 	if (FUID_INDEX(id)) {
3101 		char *domain;
3102 
3103 		domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
3104 		(void) printf("\t%s     %llx [%s-%d]\n", id_type,
3105 		    (u_longlong_t)id, domain, (int)FUID_RID(id));
3106 	} else {
3107 		(void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
3108 	}
3109 
3110 }
3111 
3112 static void
3113 dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
3114 {
3115 	uint32_t uid_idx, gid_idx;
3116 
3117 	uid_idx = FUID_INDEX(uid);
3118 	gid_idx = FUID_INDEX(gid);
3119 
3120 	/* Load domain table, if not already loaded */
3121 	if (!fuid_table_loaded && (uid_idx || gid_idx)) {
3122 		uint64_t fuid_obj;
3123 
3124 		/* first find the fuid object.  It lives in the master node */
3125 		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
3126 		    8, 1, &fuid_obj) == 0);
3127 		zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
3128 		(void) zfs_fuid_table_load(os, fuid_obj,
3129 		    &idx_tree, &domain_tree);
3130 		fuid_table_loaded = B_TRUE;
3131 	}
3132 
3133 	print_idstr(uid, "uid");
3134 	print_idstr(gid, "gid");
3135 }
3136 
3137 static void
3138 dump_znode_sa_xattr(sa_handle_t *hdl)
3139 {
3140 	nvlist_t *sa_xattr;
3141 	nvpair_t *elem = NULL;
3142 	int sa_xattr_size = 0;
3143 	int sa_xattr_entries = 0;
3144 	int error;
3145 	char *sa_xattr_packed;
3146 
3147 	error = sa_size(hdl, sa_attr_table[ZPL_DXATTR], &sa_xattr_size);
3148 	if (error || sa_xattr_size == 0)
3149 		return;
3150 
3151 	sa_xattr_packed = malloc(sa_xattr_size);
3152 	if (sa_xattr_packed == NULL)
3153 		return;
3154 
3155 	error = sa_lookup(hdl, sa_attr_table[ZPL_DXATTR],
3156 	    sa_xattr_packed, sa_xattr_size);
3157 	if (error) {
3158 		free(sa_xattr_packed);
3159 		return;
3160 	}
3161 
3162 	error = nvlist_unpack(sa_xattr_packed, sa_xattr_size, &sa_xattr, 0);
3163 	if (error) {
3164 		free(sa_xattr_packed);
3165 		return;
3166 	}
3167 
3168 	while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL)
3169 		sa_xattr_entries++;
3170 
3171 	(void) printf("\tSA xattrs: %d bytes, %d entries\n\n",
3172 	    sa_xattr_size, sa_xattr_entries);
3173 	while ((elem = nvlist_next_nvpair(sa_xattr, elem)) != NULL) {
3174 		uchar_t *value;
3175 		uint_t cnt, idx;
3176 
3177 		(void) printf("\t\t%s = ", nvpair_name(elem));
3178 		nvpair_value_byte_array(elem, &value, &cnt);
3179 		for (idx = 0; idx < cnt; ++idx) {
3180 			if (isprint(value[idx]))
3181 				(void) putchar(value[idx]);
3182 			else
3183 				(void) printf("\\%3.3o", value[idx]);
3184 		}
3185 		(void) putchar('\n');
3186 	}
3187 
3188 	nvlist_free(sa_xattr);
3189 	free(sa_xattr_packed);
3190 }
3191 
3192 static void
3193 dump_znode_symlink(sa_handle_t *hdl)
3194 {
3195 	int sa_symlink_size = 0;
3196 	char linktarget[MAXPATHLEN];
3197 	linktarget[0] = '\0';
3198 	int error;
3199 
3200 	error = sa_size(hdl, sa_attr_table[ZPL_SYMLINK], &sa_symlink_size);
3201 	if (error || sa_symlink_size == 0) {
3202 		return;
3203 	}
3204 	if (sa_lookup(hdl, sa_attr_table[ZPL_SYMLINK],
3205 	    &linktarget, sa_symlink_size) == 0)
3206 		(void) printf("\ttarget	%s\n", linktarget);
3207 }
3208 
3209 static void
3210 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
3211 {
3212 	(void) data, (void) size;
3213 	char path[MAXPATHLEN * 2];	/* allow for xattr and failure prefix */
3214 	sa_handle_t *hdl;
3215 	uint64_t xattr, rdev, gen;
3216 	uint64_t uid, gid, mode, fsize, parent, links;
3217 	uint64_t pflags;
3218 	uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
3219 	time_t z_crtime, z_atime, z_mtime, z_ctime;
3220 	sa_bulk_attr_t bulk[12];
3221 	int idx = 0;
3222 	int error;
3223 
3224 	VERIFY3P(os, ==, sa_os);
3225 	if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
3226 		(void) printf("Failed to get handle for SA znode\n");
3227 		return;
3228 	}
3229 
3230 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
3231 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
3232 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
3233 	    &links, 8);
3234 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
3235 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
3236 	    &mode, 8);
3237 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
3238 	    NULL, &parent, 8);
3239 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
3240 	    &fsize, 8);
3241 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
3242 	    acctm, 16);
3243 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
3244 	    modtm, 16);
3245 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
3246 	    crtm, 16);
3247 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
3248 	    chgtm, 16);
3249 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
3250 	    &pflags, 8);
3251 
3252 	if (sa_bulk_lookup(hdl, bulk, idx)) {
3253 		(void) sa_handle_destroy(hdl);
3254 		return;
3255 	}
3256 
3257 	z_crtime = (time_t)crtm[0];
3258 	z_atime = (time_t)acctm[0];
3259 	z_mtime = (time_t)modtm[0];
3260 	z_ctime = (time_t)chgtm[0];
3261 
3262 	if (dump_opt['d'] > 4) {
3263 		error = zfs_obj_to_path(os, object, path, sizeof (path));
3264 		if (error == ESTALE) {
3265 			(void) snprintf(path, sizeof (path), "on delete queue");
3266 		} else if (error != 0) {
3267 			leaked_objects++;
3268 			(void) snprintf(path, sizeof (path),
3269 			    "path not found, possibly leaked");
3270 		}
3271 		(void) printf("\tpath	%s\n", path);
3272 	}
3273 
3274 	if (S_ISLNK(mode))
3275 		dump_znode_symlink(hdl);
3276 	dump_uidgid(os, uid, gid);
3277 	(void) printf("\tatime	%s", ctime(&z_atime));
3278 	(void) printf("\tmtime	%s", ctime(&z_mtime));
3279 	(void) printf("\tctime	%s", ctime(&z_ctime));
3280 	(void) printf("\tcrtime	%s", ctime(&z_crtime));
3281 	(void) printf("\tgen	%llu\n", (u_longlong_t)gen);
3282 	(void) printf("\tmode	%llo\n", (u_longlong_t)mode);
3283 	(void) printf("\tsize	%llu\n", (u_longlong_t)fsize);
3284 	(void) printf("\tparent	%llu\n", (u_longlong_t)parent);
3285 	(void) printf("\tlinks	%llu\n", (u_longlong_t)links);
3286 	(void) printf("\tpflags	%llx\n", (u_longlong_t)pflags);
3287 	if (dmu_objset_projectquota_enabled(os) && (pflags & ZFS_PROJID)) {
3288 		uint64_t projid;
3289 
3290 		if (sa_lookup(hdl, sa_attr_table[ZPL_PROJID], &projid,
3291 		    sizeof (uint64_t)) == 0)
3292 			(void) printf("\tprojid	%llu\n", (u_longlong_t)projid);
3293 	}
3294 	if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
3295 	    sizeof (uint64_t)) == 0)
3296 		(void) printf("\txattr	%llu\n", (u_longlong_t)xattr);
3297 	if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
3298 	    sizeof (uint64_t)) == 0)
3299 		(void) printf("\trdev	0x%016llx\n", (u_longlong_t)rdev);
3300 	dump_znode_sa_xattr(hdl);
3301 	sa_handle_destroy(hdl);
3302 }
3303 
3304 static void
3305 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
3306 {
3307 	(void) os, (void) object, (void) data, (void) size;
3308 }
3309 
3310 static void
3311 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
3312 {
3313 	(void) os, (void) object, (void) data, (void) size;
3314 }
3315 
3316 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
3317 	dump_none,		/* unallocated			*/
3318 	dump_zap,		/* object directory		*/
3319 	dump_uint64,		/* object array			*/
3320 	dump_none,		/* packed nvlist		*/
3321 	dump_packed_nvlist,	/* packed nvlist size		*/
3322 	dump_none,		/* bpobj			*/
3323 	dump_bpobj,		/* bpobj header			*/
3324 	dump_none,		/* SPA space map header		*/
3325 	dump_none,		/* SPA space map		*/
3326 	dump_none,		/* ZIL intent log		*/
3327 	dump_dnode,		/* DMU dnode			*/
3328 	dump_dmu_objset,	/* DMU objset			*/
3329 	dump_dsl_dir,		/* DSL directory		*/
3330 	dump_zap,		/* DSL directory child map	*/
3331 	dump_zap,		/* DSL dataset snap map		*/
3332 	dump_zap,		/* DSL props			*/
3333 	dump_dsl_dataset,	/* DSL dataset			*/
3334 	dump_znode,		/* ZFS znode			*/
3335 	dump_acl,		/* ZFS V0 ACL			*/
3336 	dump_uint8,		/* ZFS plain file		*/
3337 	dump_zpldir,		/* ZFS directory		*/
3338 	dump_zap,		/* ZFS master node		*/
3339 	dump_zap,		/* ZFS delete queue		*/
3340 	dump_uint8,		/* zvol object			*/
3341 	dump_zap,		/* zvol prop			*/
3342 	dump_uint8,		/* other uint8[]		*/
3343 	dump_uint64,		/* other uint64[]		*/
3344 	dump_zap,		/* other ZAP			*/
3345 	dump_zap,		/* persistent error log		*/
3346 	dump_uint8,		/* SPA history			*/
3347 	dump_history_offsets,	/* SPA history offsets		*/
3348 	dump_zap,		/* Pool properties		*/
3349 	dump_zap,		/* DSL permissions		*/
3350 	dump_acl,		/* ZFS ACL			*/
3351 	dump_uint8,		/* ZFS SYSACL			*/
3352 	dump_none,		/* FUID nvlist			*/
3353 	dump_packed_nvlist,	/* FUID nvlist size		*/
3354 	dump_zap,		/* DSL dataset next clones	*/
3355 	dump_zap,		/* DSL scrub queue		*/
3356 	dump_zap,		/* ZFS user/group/project used	*/
3357 	dump_zap,		/* ZFS user/group/project quota	*/
3358 	dump_zap,		/* snapshot refcount tags	*/
3359 	dump_ddt_zap,		/* DDT ZAP object		*/
3360 	dump_zap,		/* DDT statistics		*/
3361 	dump_znode,		/* SA object			*/
3362 	dump_zap,		/* SA Master Node		*/
3363 	dump_sa_attrs,		/* SA attribute registration	*/
3364 	dump_sa_layouts,	/* SA attribute layouts		*/
3365 	dump_zap,		/* DSL scrub translations	*/
3366 	dump_none,		/* fake dedup BP		*/
3367 	dump_zap,		/* deadlist			*/
3368 	dump_none,		/* deadlist hdr			*/
3369 	dump_zap,		/* dsl clones			*/
3370 	dump_bpobj_subobjs,	/* bpobj subobjs		*/
3371 	dump_unknown,		/* Unknown type, must be last	*/
3372 };
3373 
3374 static boolean_t
3375 match_object_type(dmu_object_type_t obj_type, uint64_t flags)
3376 {
3377 	boolean_t match = B_TRUE;
3378 
3379 	switch (obj_type) {
3380 	case DMU_OT_DIRECTORY_CONTENTS:
3381 		if (!(flags & ZOR_FLAG_DIRECTORY))
3382 			match = B_FALSE;
3383 		break;
3384 	case DMU_OT_PLAIN_FILE_CONTENTS:
3385 		if (!(flags & ZOR_FLAG_PLAIN_FILE))
3386 			match = B_FALSE;
3387 		break;
3388 	case DMU_OT_SPACE_MAP:
3389 		if (!(flags & ZOR_FLAG_SPACE_MAP))
3390 			match = B_FALSE;
3391 		break;
3392 	default:
3393 		if (strcmp(zdb_ot_name(obj_type), "zap") == 0) {
3394 			if (!(flags & ZOR_FLAG_ZAP))
3395 				match = B_FALSE;
3396 			break;
3397 		}
3398 
3399 		/*
3400 		 * If all bits except some of the supported flags are
3401 		 * set, the user combined the all-types flag (A) with
3402 		 * a negated flag to exclude some types (e.g. A-f to
3403 		 * show all object types except plain files).
3404 		 */
3405 		if ((flags | ZOR_SUPPORTED_FLAGS) != ZOR_FLAG_ALL_TYPES)
3406 			match = B_FALSE;
3407 
3408 		break;
3409 	}
3410 
3411 	return (match);
3412 }
3413 
3414 static void
3415 dump_object(objset_t *os, uint64_t object, int verbosity,
3416     boolean_t *print_header, uint64_t *dnode_slots_used, uint64_t flags)
3417 {
3418 	dmu_buf_t *db = NULL;
3419 	dmu_object_info_t doi;
3420 	dnode_t *dn;
3421 	boolean_t dnode_held = B_FALSE;
3422 	void *bonus = NULL;
3423 	size_t bsize = 0;
3424 	char iblk[32], dblk[32], lsize[32], asize[32], fill[32], dnsize[32];
3425 	char bonus_size[32];
3426 	char aux[50];
3427 	int error;
3428 
3429 	/* make sure nicenum has enough space */
3430 	_Static_assert(sizeof (iblk) >= NN_NUMBUF_SZ, "iblk truncated");
3431 	_Static_assert(sizeof (dblk) >= NN_NUMBUF_SZ, "dblk truncated");
3432 	_Static_assert(sizeof (lsize) >= NN_NUMBUF_SZ, "lsize truncated");
3433 	_Static_assert(sizeof (asize) >= NN_NUMBUF_SZ, "asize truncated");
3434 	_Static_assert(sizeof (bonus_size) >= NN_NUMBUF_SZ,
3435 	    "bonus_size truncated");
3436 
3437 	if (*print_header) {
3438 		(void) printf("\n%10s  %3s  %5s  %5s  %5s  %6s  %5s  %6s  %s\n",
3439 		    "Object", "lvl", "iblk", "dblk", "dsize", "dnsize",
3440 		    "lsize", "%full", "type");
3441 		*print_header = 0;
3442 	}
3443 
3444 	if (object == 0) {
3445 		dn = DMU_META_DNODE(os);
3446 		dmu_object_info_from_dnode(dn, &doi);
3447 	} else {
3448 		/*
3449 		 * Encrypted datasets will have sensitive bonus buffers
3450 		 * encrypted. Therefore we cannot hold the bonus buffer and
3451 		 * must hold the dnode itself instead.
3452 		 */
3453 		error = dmu_object_info(os, object, &doi);
3454 		if (error)
3455 			fatal("dmu_object_info() failed, errno %u", error);
3456 
3457 		if (os->os_encrypted &&
3458 		    DMU_OT_IS_ENCRYPTED(doi.doi_bonus_type)) {
3459 			error = dnode_hold(os, object, FTAG, &dn);
3460 			if (error)
3461 				fatal("dnode_hold() failed, errno %u", error);
3462 			dnode_held = B_TRUE;
3463 		} else {
3464 			error = dmu_bonus_hold(os, object, FTAG, &db);
3465 			if (error)
3466 				fatal("dmu_bonus_hold(%llu) failed, errno %u",
3467 				    object, error);
3468 			bonus = db->db_data;
3469 			bsize = db->db_size;
3470 			dn = DB_DNODE((dmu_buf_impl_t *)db);
3471 		}
3472 	}
3473 
3474 	/*
3475 	 * Default to showing all object types if no flags were specified.
3476 	 */
3477 	if (flags != 0 && flags != ZOR_FLAG_ALL_TYPES &&
3478 	    !match_object_type(doi.doi_type, flags))
3479 		goto out;
3480 
3481 	if (dnode_slots_used)
3482 		*dnode_slots_used = doi.doi_dnodesize / DNODE_MIN_SIZE;
3483 
3484 	zdb_nicenum(doi.doi_metadata_block_size, iblk, sizeof (iblk));
3485 	zdb_nicenum(doi.doi_data_block_size, dblk, sizeof (dblk));
3486 	zdb_nicenum(doi.doi_max_offset, lsize, sizeof (lsize));
3487 	zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize, sizeof (asize));
3488 	zdb_nicenum(doi.doi_bonus_size, bonus_size, sizeof (bonus_size));
3489 	zdb_nicenum(doi.doi_dnodesize, dnsize, sizeof (dnsize));
3490 	(void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
3491 	    doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
3492 	    doi.doi_max_offset);
3493 
3494 	aux[0] = '\0';
3495 
3496 	if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
3497 		(void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
3498 		    " (K=%s)", ZDB_CHECKSUM_NAME(doi.doi_checksum));
3499 	}
3500 
3501 	if (doi.doi_compress == ZIO_COMPRESS_INHERIT &&
3502 	    ZIO_COMPRESS_HASLEVEL(os->os_compress) && verbosity >= 6) {
3503 		const char *compname = NULL;
3504 		if (zfs_prop_index_to_string(ZFS_PROP_COMPRESSION,
3505 		    ZIO_COMPRESS_RAW(os->os_compress, os->os_complevel),
3506 		    &compname) == 0) {
3507 			(void) snprintf(aux + strlen(aux),
3508 			    sizeof (aux) - strlen(aux), " (Z=inherit=%s)",
3509 			    compname);
3510 		} else {
3511 			(void) snprintf(aux + strlen(aux),
3512 			    sizeof (aux) - strlen(aux),
3513 			    " (Z=inherit=%s-unknown)",
3514 			    ZDB_COMPRESS_NAME(os->os_compress));
3515 		}
3516 	} else if (doi.doi_compress == ZIO_COMPRESS_INHERIT && verbosity >= 6) {
3517 		(void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
3518 		    " (Z=inherit=%s)", ZDB_COMPRESS_NAME(os->os_compress));
3519 	} else if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
3520 		(void) snprintf(aux + strlen(aux), sizeof (aux) - strlen(aux),
3521 		    " (Z=%s)", ZDB_COMPRESS_NAME(doi.doi_compress));
3522 	}
3523 
3524 	(void) printf("%10lld  %3u  %5s  %5s  %5s  %6s  %5s  %6s  %s%s\n",
3525 	    (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
3526 	    asize, dnsize, lsize, fill, zdb_ot_name(doi.doi_type), aux);
3527 
3528 	if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
3529 		(void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %5s  %6s  %s\n",
3530 		    "", "", "", "", "", "", bonus_size, "bonus",
3531 		    zdb_ot_name(doi.doi_bonus_type));
3532 	}
3533 
3534 	if (verbosity >= 4) {
3535 		(void) printf("\tdnode flags: %s%s%s%s\n",
3536 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
3537 		    "USED_BYTES " : "",
3538 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
3539 		    "USERUSED_ACCOUNTED " : "",
3540 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USEROBJUSED_ACCOUNTED) ?
3541 		    "USEROBJUSED_ACCOUNTED " : "",
3542 		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
3543 		    "SPILL_BLKPTR" : "");
3544 		(void) printf("\tdnode maxblkid: %llu\n",
3545 		    (longlong_t)dn->dn_phys->dn_maxblkid);
3546 
3547 		if (!dnode_held) {
3548 			object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os,
3549 			    object, bonus, bsize);
3550 		} else {
3551 			(void) printf("\t\t(bonus encrypted)\n");
3552 		}
3553 
3554 		if (!os->os_encrypted || !DMU_OT_IS_ENCRYPTED(doi.doi_type)) {
3555 			object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object,
3556 			    NULL, 0);
3557 		} else {
3558 			(void) printf("\t\t(object encrypted)\n");
3559 		}
3560 
3561 		*print_header = B_TRUE;
3562 	}
3563 
3564 	if (verbosity >= 5)
3565 		dump_indirect(dn);
3566 
3567 	if (verbosity >= 5) {
3568 		/*
3569 		 * Report the list of segments that comprise the object.
3570 		 */
3571 		uint64_t start = 0;
3572 		uint64_t end;
3573 		uint64_t blkfill = 1;
3574 		int minlvl = 1;
3575 
3576 		if (dn->dn_type == DMU_OT_DNODE) {
3577 			minlvl = 0;
3578 			blkfill = DNODES_PER_BLOCK;
3579 		}
3580 
3581 		for (;;) {
3582 			char segsize[32];
3583 			/* make sure nicenum has enough space */
3584 			_Static_assert(sizeof (segsize) >= NN_NUMBUF_SZ,
3585 			    "segsize truncated");
3586 			error = dnode_next_offset(dn,
3587 			    0, &start, minlvl, blkfill, 0);
3588 			if (error)
3589 				break;
3590 			end = start;
3591 			error = dnode_next_offset(dn,
3592 			    DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
3593 			zdb_nicenum(end - start, segsize, sizeof (segsize));
3594 			(void) printf("\t\tsegment [%016llx, %016llx)"
3595 			    " size %5s\n", (u_longlong_t)start,
3596 			    (u_longlong_t)end, segsize);
3597 			if (error)
3598 				break;
3599 			start = end;
3600 		}
3601 	}
3602 
3603 out:
3604 	if (db != NULL)
3605 		dmu_buf_rele(db, FTAG);
3606 	if (dnode_held)
3607 		dnode_rele(dn, FTAG);
3608 }
3609 
3610 static void
3611 count_dir_mos_objects(dsl_dir_t *dd)
3612 {
3613 	mos_obj_refd(dd->dd_object);
3614 	mos_obj_refd(dsl_dir_phys(dd)->dd_child_dir_zapobj);
3615 	mos_obj_refd(dsl_dir_phys(dd)->dd_deleg_zapobj);
3616 	mos_obj_refd(dsl_dir_phys(dd)->dd_props_zapobj);
3617 	mos_obj_refd(dsl_dir_phys(dd)->dd_clones);
3618 
3619 	/*
3620 	 * The dd_crypto_obj can be referenced by multiple dsl_dir's.
3621 	 * Ignore the references after the first one.
3622 	 */
3623 	mos_obj_refd_multiple(dd->dd_crypto_obj);
3624 }
3625 
3626 static void
3627 count_ds_mos_objects(dsl_dataset_t *ds)
3628 {
3629 	mos_obj_refd(ds->ds_object);
3630 	mos_obj_refd(dsl_dataset_phys(ds)->ds_next_clones_obj);
3631 	mos_obj_refd(dsl_dataset_phys(ds)->ds_props_obj);
3632 	mos_obj_refd(dsl_dataset_phys(ds)->ds_userrefs_obj);
3633 	mos_obj_refd(dsl_dataset_phys(ds)->ds_snapnames_zapobj);
3634 	mos_obj_refd(ds->ds_bookmarks_obj);
3635 
3636 	if (!dsl_dataset_is_snapshot(ds)) {
3637 		count_dir_mos_objects(ds->ds_dir);
3638 	}
3639 }
3640 
3641 static const char *objset_types[DMU_OST_NUMTYPES] = {
3642 	"NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
3643 
3644 /*
3645  * Parse a string denoting a range of object IDs of the form
3646  * <start>[:<end>[:flags]], and store the results in zor.
3647  * Return 0 on success. On error, return 1 and update the msg
3648  * pointer to point to a descriptive error message.
3649  */
3650 static int
3651 parse_object_range(char *range, zopt_object_range_t *zor, char **msg)
3652 {
3653 	uint64_t flags = 0;
3654 	char *p, *s, *dup, *flagstr, *tmp = NULL;
3655 	size_t len;
3656 	int i;
3657 	int rc = 0;
3658 
3659 	if (strchr(range, ':') == NULL) {
3660 		zor->zor_obj_start = strtoull(range, &p, 0);
3661 		if (*p != '\0') {
3662 			*msg = "Invalid characters in object ID";
3663 			rc = 1;
3664 		}
3665 		zor->zor_obj_start = ZDB_MAP_OBJECT_ID(zor->zor_obj_start);
3666 		zor->zor_obj_end = zor->zor_obj_start;
3667 		return (rc);
3668 	}
3669 
3670 	if (strchr(range, ':') == range) {
3671 		*msg = "Invalid leading colon";
3672 		rc = 1;
3673 		return (rc);
3674 	}
3675 
3676 	len = strlen(range);
3677 	if (range[len - 1] == ':') {
3678 		*msg = "Invalid trailing colon";
3679 		rc = 1;
3680 		return (rc);
3681 	}
3682 
3683 	dup = strdup(range);
3684 	s = strtok_r(dup, ":", &tmp);
3685 	zor->zor_obj_start = strtoull(s, &p, 0);
3686 
3687 	if (*p != '\0') {
3688 		*msg = "Invalid characters in start object ID";
3689 		rc = 1;
3690 		goto out;
3691 	}
3692 
3693 	s = strtok_r(NULL, ":", &tmp);
3694 	zor->zor_obj_end = strtoull(s, &p, 0);
3695 
3696 	if (*p != '\0') {
3697 		*msg = "Invalid characters in end object ID";
3698 		rc = 1;
3699 		goto out;
3700 	}
3701 
3702 	if (zor->zor_obj_start > zor->zor_obj_end) {
3703 		*msg = "Start object ID may not exceed end object ID";
3704 		rc = 1;
3705 		goto out;
3706 	}
3707 
3708 	s = strtok_r(NULL, ":", &tmp);
3709 	if (s == NULL) {
3710 		zor->zor_flags = ZOR_FLAG_ALL_TYPES;
3711 		goto out;
3712 	} else if (strtok_r(NULL, ":", &tmp) != NULL) {
3713 		*msg = "Invalid colon-delimited field after flags";
3714 		rc = 1;
3715 		goto out;
3716 	}
3717 
3718 	flagstr = s;
3719 	for (i = 0; flagstr[i]; i++) {
3720 		int bit;
3721 		boolean_t negation = (flagstr[i] == '-');
3722 
3723 		if (negation) {
3724 			i++;
3725 			if (flagstr[i] == '\0') {
3726 				*msg = "Invalid trailing negation operator";
3727 				rc = 1;
3728 				goto out;
3729 			}
3730 		}
3731 		bit = flagbits[(uchar_t)flagstr[i]];
3732 		if (bit == 0) {
3733 			*msg = "Invalid flag";
3734 			rc = 1;
3735 			goto out;
3736 		}
3737 		if (negation)
3738 			flags &= ~bit;
3739 		else
3740 			flags |= bit;
3741 	}
3742 	zor->zor_flags = flags;
3743 
3744 	zor->zor_obj_start = ZDB_MAP_OBJECT_ID(zor->zor_obj_start);
3745 	zor->zor_obj_end = ZDB_MAP_OBJECT_ID(zor->zor_obj_end);
3746 
3747 out:
3748 	free(dup);
3749 	return (rc);
3750 }
3751 
3752 static void
3753 dump_objset(objset_t *os)
3754 {
3755 	dmu_objset_stats_t dds = { 0 };
3756 	uint64_t object, object_count;
3757 	uint64_t refdbytes, usedobjs, scratch;
3758 	char numbuf[32];
3759 	char blkbuf[BP_SPRINTF_LEN + 20];
3760 	char osname[ZFS_MAX_DATASET_NAME_LEN];
3761 	const char *type = "UNKNOWN";
3762 	int verbosity = dump_opt['d'];
3763 	boolean_t print_header;
3764 	unsigned i;
3765 	int error;
3766 	uint64_t total_slots_used = 0;
3767 	uint64_t max_slot_used = 0;
3768 	uint64_t dnode_slots;
3769 	uint64_t obj_start;
3770 	uint64_t obj_end;
3771 	uint64_t flags;
3772 
3773 	/* make sure nicenum has enough space */
3774 	_Static_assert(sizeof (numbuf) >= NN_NUMBUF_SZ, "numbuf truncated");
3775 
3776 	dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
3777 	dmu_objset_fast_stat(os, &dds);
3778 	dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
3779 
3780 	print_header = B_TRUE;
3781 
3782 	if (dds.dds_type < DMU_OST_NUMTYPES)
3783 		type = objset_types[dds.dds_type];
3784 
3785 	if (dds.dds_type == DMU_OST_META) {
3786 		dds.dds_creation_txg = TXG_INITIAL;
3787 		usedobjs = BP_GET_FILL(os->os_rootbp);
3788 		refdbytes = dsl_dir_phys(os->os_spa->spa_dsl_pool->dp_mos_dir)->
3789 		    dd_used_bytes;
3790 	} else {
3791 		dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
3792 	}
3793 
3794 	ASSERT3U(usedobjs, ==, BP_GET_FILL(os->os_rootbp));
3795 
3796 	zdb_nicenum(refdbytes, numbuf, sizeof (numbuf));
3797 
3798 	if (verbosity >= 4) {
3799 		(void) snprintf(blkbuf, sizeof (blkbuf), ", rootbp ");
3800 		(void) snprintf_blkptr(blkbuf + strlen(blkbuf),
3801 		    sizeof (blkbuf) - strlen(blkbuf), os->os_rootbp);
3802 	} else {
3803 		blkbuf[0] = '\0';
3804 	}
3805 
3806 	dmu_objset_name(os, osname);
3807 
3808 	(void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
3809 	    "%s, %llu objects%s%s\n",
3810 	    osname, type, (u_longlong_t)dmu_objset_id(os),
3811 	    (u_longlong_t)dds.dds_creation_txg,
3812 	    numbuf, (u_longlong_t)usedobjs, blkbuf,
3813 	    (dds.dds_inconsistent) ? " (inconsistent)" : "");
3814 
3815 	for (i = 0; i < zopt_object_args; i++) {
3816 		obj_start = zopt_object_ranges[i].zor_obj_start;
3817 		obj_end = zopt_object_ranges[i].zor_obj_end;
3818 		flags = zopt_object_ranges[i].zor_flags;
3819 
3820 		object = obj_start;
3821 		if (object == 0 || obj_start == obj_end)
3822 			dump_object(os, object, verbosity, &print_header, NULL,
3823 			    flags);
3824 		else
3825 			object--;
3826 
3827 		while ((dmu_object_next(os, &object, B_FALSE, 0) == 0) &&
3828 		    object <= obj_end) {
3829 			dump_object(os, object, verbosity, &print_header, NULL,
3830 			    flags);
3831 		}
3832 	}
3833 
3834 	if (zopt_object_args > 0) {
3835 		(void) printf("\n");
3836 		return;
3837 	}
3838 
3839 	if (dump_opt['i'] != 0 || verbosity >= 2)
3840 		dump_intent_log(dmu_objset_zil(os));
3841 
3842 	if (dmu_objset_ds(os) != NULL) {
3843 		dsl_dataset_t *ds = dmu_objset_ds(os);
3844 		dump_blkptr_list(&ds->ds_deadlist, "Deadlist");
3845 		if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist) &&
3846 		    !dmu_objset_is_snapshot(os)) {
3847 			dump_blkptr_list(&ds->ds_dir->dd_livelist, "Livelist");
3848 			if (verify_dd_livelist(os) != 0)
3849 				fatal("livelist is incorrect");
3850 		}
3851 
3852 		if (dsl_dataset_remap_deadlist_exists(ds)) {
3853 			(void) printf("ds_remap_deadlist:\n");
3854 			dump_blkptr_list(&ds->ds_remap_deadlist, "Deadlist");
3855 		}
3856 		count_ds_mos_objects(ds);
3857 	}
3858 
3859 	if (dmu_objset_ds(os) != NULL)
3860 		dump_bookmarks(os, verbosity);
3861 
3862 	if (verbosity < 2)
3863 		return;
3864 
3865 	if (BP_IS_HOLE(os->os_rootbp))
3866 		return;
3867 
3868 	dump_object(os, 0, verbosity, &print_header, NULL, 0);
3869 	object_count = 0;
3870 	if (DMU_USERUSED_DNODE(os) != NULL &&
3871 	    DMU_USERUSED_DNODE(os)->dn_type != 0) {
3872 		dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header,
3873 		    NULL, 0);
3874 		dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header,
3875 		    NULL, 0);
3876 	}
3877 
3878 	if (DMU_PROJECTUSED_DNODE(os) != NULL &&
3879 	    DMU_PROJECTUSED_DNODE(os)->dn_type != 0)
3880 		dump_object(os, DMU_PROJECTUSED_OBJECT, verbosity,
3881 		    &print_header, NULL, 0);
3882 
3883 	object = 0;
3884 	while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
3885 		dump_object(os, object, verbosity, &print_header, &dnode_slots,
3886 		    0);
3887 		object_count++;
3888 		total_slots_used += dnode_slots;
3889 		max_slot_used = object + dnode_slots - 1;
3890 	}
3891 
3892 	(void) printf("\n");
3893 
3894 	(void) printf("    Dnode slots:\n");
3895 	(void) printf("\tTotal used:    %10llu\n",
3896 	    (u_longlong_t)total_slots_used);
3897 	(void) printf("\tMax used:      %10llu\n",
3898 	    (u_longlong_t)max_slot_used);
3899 	(void) printf("\tPercent empty: %10lf\n",
3900 	    (double)(max_slot_used - total_slots_used)*100 /
3901 	    (double)max_slot_used);
3902 	(void) printf("\n");
3903 
3904 	if (error != ESRCH) {
3905 		(void) fprintf(stderr, "dmu_object_next() = %d\n", error);
3906 		abort();
3907 	}
3908 
3909 	ASSERT3U(object_count, ==, usedobjs);
3910 
3911 	if (leaked_objects != 0) {
3912 		(void) printf("%d potentially leaked objects detected\n",
3913 		    leaked_objects);
3914 		leaked_objects = 0;
3915 	}
3916 }
3917 
3918 static void
3919 dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
3920 {
3921 	time_t timestamp = ub->ub_timestamp;
3922 
3923 	(void) printf("%s", header ? header : "");
3924 	(void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
3925 	(void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
3926 	(void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
3927 	(void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
3928 	(void) printf("\ttimestamp = %llu UTC = %s",
3929 	    (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
3930 
3931 	(void) printf("\tmmp_magic = %016llx\n",
3932 	    (u_longlong_t)ub->ub_mmp_magic);
3933 	if (MMP_VALID(ub)) {
3934 		(void) printf("\tmmp_delay = %0llu\n",
3935 		    (u_longlong_t)ub->ub_mmp_delay);
3936 		if (MMP_SEQ_VALID(ub))
3937 			(void) printf("\tmmp_seq = %u\n",
3938 			    (unsigned int) MMP_SEQ(ub));
3939 		if (MMP_FAIL_INT_VALID(ub))
3940 			(void) printf("\tmmp_fail = %u\n",
3941 			    (unsigned int) MMP_FAIL_INT(ub));
3942 		if (MMP_INTERVAL_VALID(ub))
3943 			(void) printf("\tmmp_write = %u\n",
3944 			    (unsigned int) MMP_INTERVAL(ub));
3945 		/* After MMP_* to make summarize_uberblock_mmp cleaner */
3946 		(void) printf("\tmmp_valid = %x\n",
3947 		    (unsigned int) ub->ub_mmp_config & 0xFF);
3948 	}
3949 
3950 	if (dump_opt['u'] >= 4) {
3951 		char blkbuf[BP_SPRINTF_LEN];
3952 		snprintf_blkptr(blkbuf, sizeof (blkbuf), &ub->ub_rootbp);
3953 		(void) printf("\trootbp = %s\n", blkbuf);
3954 	}
3955 	(void) printf("\tcheckpoint_txg = %llu\n",
3956 	    (u_longlong_t)ub->ub_checkpoint_txg);
3957 	(void) printf("%s", footer ? footer : "");
3958 }
3959 
3960 static void
3961 dump_config(spa_t *spa)
3962 {
3963 	dmu_buf_t *db;
3964 	size_t nvsize = 0;
3965 	int error = 0;
3966 
3967 
3968 	error = dmu_bonus_hold(spa->spa_meta_objset,
3969 	    spa->spa_config_object, FTAG, &db);
3970 
3971 	if (error == 0) {
3972 		nvsize = *(uint64_t *)db->db_data;
3973 		dmu_buf_rele(db, FTAG);
3974 
3975 		(void) printf("\nMOS Configuration:\n");
3976 		dump_packed_nvlist(spa->spa_meta_objset,
3977 		    spa->spa_config_object, (void *)&nvsize, 1);
3978 	} else {
3979 		(void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
3980 		    (u_longlong_t)spa->spa_config_object, error);
3981 	}
3982 }
3983 
3984 static void
3985 dump_cachefile(const char *cachefile)
3986 {
3987 	int fd;
3988 	struct stat64 statbuf;
3989 	char *buf;
3990 	nvlist_t *config;
3991 
3992 	if ((fd = open64(cachefile, O_RDONLY)) < 0) {
3993 		(void) printf("cannot open '%s': %s\n", cachefile,
3994 		    strerror(errno));
3995 		exit(1);
3996 	}
3997 
3998 	if (fstat64(fd, &statbuf) != 0) {
3999 		(void) printf("failed to stat '%s': %s\n", cachefile,
4000 		    strerror(errno));
4001 		exit(1);
4002 	}
4003 
4004 	if ((buf = malloc(statbuf.st_size)) == NULL) {
4005 		(void) fprintf(stderr, "failed to allocate %llu bytes\n",
4006 		    (u_longlong_t)statbuf.st_size);
4007 		exit(1);
4008 	}
4009 
4010 	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
4011 		(void) fprintf(stderr, "failed to read %llu bytes\n",
4012 		    (u_longlong_t)statbuf.st_size);
4013 		exit(1);
4014 	}
4015 
4016 	(void) close(fd);
4017 
4018 	if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
4019 		(void) fprintf(stderr, "failed to unpack nvlist\n");
4020 		exit(1);
4021 	}
4022 
4023 	free(buf);
4024 
4025 	dump_nvlist(config, 0);
4026 
4027 	nvlist_free(config);
4028 }
4029 
4030 /*
4031  * ZFS label nvlist stats
4032  */
4033 typedef struct zdb_nvl_stats {
4034 	int		zns_list_count;
4035 	int		zns_leaf_count;
4036 	size_t		zns_leaf_largest;
4037 	size_t		zns_leaf_total;
4038 	nvlist_t	*zns_string;
4039 	nvlist_t	*zns_uint64;
4040 	nvlist_t	*zns_boolean;
4041 } zdb_nvl_stats_t;
4042 
4043 static void
4044 collect_nvlist_stats(nvlist_t *nvl, zdb_nvl_stats_t *stats)
4045 {
4046 	nvlist_t *list, **array;
4047 	nvpair_t *nvp = NULL;
4048 	char *name;
4049 	uint_t i, items;
4050 
4051 	stats->zns_list_count++;
4052 
4053 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4054 		name = nvpair_name(nvp);
4055 
4056 		switch (nvpair_type(nvp)) {
4057 		case DATA_TYPE_STRING:
4058 			fnvlist_add_string(stats->zns_string, name,
4059 			    fnvpair_value_string(nvp));
4060 			break;
4061 		case DATA_TYPE_UINT64:
4062 			fnvlist_add_uint64(stats->zns_uint64, name,
4063 			    fnvpair_value_uint64(nvp));
4064 			break;
4065 		case DATA_TYPE_BOOLEAN:
4066 			fnvlist_add_boolean(stats->zns_boolean, name);
4067 			break;
4068 		case DATA_TYPE_NVLIST:
4069 			if (nvpair_value_nvlist(nvp, &list) == 0)
4070 				collect_nvlist_stats(list, stats);
4071 			break;
4072 		case DATA_TYPE_NVLIST_ARRAY:
4073 			if (nvpair_value_nvlist_array(nvp, &array, &items) != 0)
4074 				break;
4075 
4076 			for (i = 0; i < items; i++) {
4077 				collect_nvlist_stats(array[i], stats);
4078 
4079 				/* collect stats on leaf vdev */
4080 				if (strcmp(name, "children") == 0) {
4081 					size_t size;
4082 
4083 					(void) nvlist_size(array[i], &size,
4084 					    NV_ENCODE_XDR);
4085 					stats->zns_leaf_total += size;
4086 					if (size > stats->zns_leaf_largest)
4087 						stats->zns_leaf_largest = size;
4088 					stats->zns_leaf_count++;
4089 				}
4090 			}
4091 			break;
4092 		default:
4093 			(void) printf("skip type %d!\n", (int)nvpair_type(nvp));
4094 		}
4095 	}
4096 }
4097 
4098 static void
4099 dump_nvlist_stats(nvlist_t *nvl, size_t cap)
4100 {
4101 	zdb_nvl_stats_t stats = { 0 };
4102 	size_t size, sum = 0, total;
4103 	size_t noise;
4104 
4105 	/* requires nvlist with non-unique names for stat collection */
4106 	VERIFY0(nvlist_alloc(&stats.zns_string, 0, 0));
4107 	VERIFY0(nvlist_alloc(&stats.zns_uint64, 0, 0));
4108 	VERIFY0(nvlist_alloc(&stats.zns_boolean, 0, 0));
4109 	VERIFY0(nvlist_size(stats.zns_boolean, &noise, NV_ENCODE_XDR));
4110 
4111 	(void) printf("\n\nZFS Label NVList Config Stats:\n");
4112 
4113 	VERIFY0(nvlist_size(nvl, &total, NV_ENCODE_XDR));
4114 	(void) printf("  %d bytes used, %d bytes free (using %4.1f%%)\n\n",
4115 	    (int)total, (int)(cap - total), 100.0 * total / cap);
4116 
4117 	collect_nvlist_stats(nvl, &stats);
4118 
4119 	VERIFY0(nvlist_size(stats.zns_uint64, &size, NV_ENCODE_XDR));
4120 	size -= noise;
4121 	sum += size;
4122 	(void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "integers:",
4123 	    (int)fnvlist_num_pairs(stats.zns_uint64),
4124 	    (int)size, 100.0 * size / total);
4125 
4126 	VERIFY0(nvlist_size(stats.zns_string, &size, NV_ENCODE_XDR));
4127 	size -= noise;
4128 	sum += size;
4129 	(void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "strings:",
4130 	    (int)fnvlist_num_pairs(stats.zns_string),
4131 	    (int)size, 100.0 * size / total);
4132 
4133 	VERIFY0(nvlist_size(stats.zns_boolean, &size, NV_ENCODE_XDR));
4134 	size -= noise;
4135 	sum += size;
4136 	(void) printf("%12s %4d %6d bytes (%5.2f%%)\n", "booleans:",
4137 	    (int)fnvlist_num_pairs(stats.zns_boolean),
4138 	    (int)size, 100.0 * size / total);
4139 
4140 	size = total - sum;	/* treat remainder as nvlist overhead */
4141 	(void) printf("%12s %4d %6d bytes (%5.2f%%)\n\n", "nvlists:",
4142 	    stats.zns_list_count, (int)size, 100.0 * size / total);
4143 
4144 	if (stats.zns_leaf_count > 0) {
4145 		size_t average = stats.zns_leaf_total / stats.zns_leaf_count;
4146 
4147 		(void) printf("%12s %4d %6d bytes average\n", "leaf vdevs:",
4148 		    stats.zns_leaf_count, (int)average);
4149 		(void) printf("%24d bytes largest\n",
4150 		    (int)stats.zns_leaf_largest);
4151 
4152 		if (dump_opt['l'] >= 3 && average > 0)
4153 			(void) printf("  space for %d additional leaf vdevs\n",
4154 			    (int)((cap - total) / average));
4155 	}
4156 	(void) printf("\n");
4157 
4158 	nvlist_free(stats.zns_string);
4159 	nvlist_free(stats.zns_uint64);
4160 	nvlist_free(stats.zns_boolean);
4161 }
4162 
4163 typedef struct cksum_record {
4164 	zio_cksum_t cksum;
4165 	boolean_t labels[VDEV_LABELS];
4166 	avl_node_t link;
4167 } cksum_record_t;
4168 
4169 static int
4170 cksum_record_compare(const void *x1, const void *x2)
4171 {
4172 	const cksum_record_t *l = (cksum_record_t *)x1;
4173 	const cksum_record_t *r = (cksum_record_t *)x2;
4174 	int arraysize = ARRAY_SIZE(l->cksum.zc_word);
4175 	int difference = 0;
4176 
4177 	for (int i = 0; i < arraysize; i++) {
4178 		difference = TREE_CMP(l->cksum.zc_word[i], r->cksum.zc_word[i]);
4179 		if (difference)
4180 			break;
4181 	}
4182 
4183 	return (difference);
4184 }
4185 
4186 static cksum_record_t *
4187 cksum_record_alloc(zio_cksum_t *cksum, int l)
4188 {
4189 	cksum_record_t *rec;
4190 
4191 	rec = umem_zalloc(sizeof (*rec), UMEM_NOFAIL);
4192 	rec->cksum = *cksum;
4193 	rec->labels[l] = B_TRUE;
4194 
4195 	return (rec);
4196 }
4197 
4198 static cksum_record_t *
4199 cksum_record_lookup(avl_tree_t *tree, zio_cksum_t *cksum)
4200 {
4201 	cksum_record_t lookup = { .cksum = *cksum };
4202 	avl_index_t where;
4203 
4204 	return (avl_find(tree, &lookup, &where));
4205 }
4206 
4207 static cksum_record_t *
4208 cksum_record_insert(avl_tree_t *tree, zio_cksum_t *cksum, int l)
4209 {
4210 	cksum_record_t *rec;
4211 
4212 	rec = cksum_record_lookup(tree, cksum);
4213 	if (rec) {
4214 		rec->labels[l] = B_TRUE;
4215 	} else {
4216 		rec = cksum_record_alloc(cksum, l);
4217 		avl_add(tree, rec);
4218 	}
4219 
4220 	return (rec);
4221 }
4222 
4223 static int
4224 first_label(cksum_record_t *rec)
4225 {
4226 	for (int i = 0; i < VDEV_LABELS; i++)
4227 		if (rec->labels[i])
4228 			return (i);
4229 
4230 	return (-1);
4231 }
4232 
4233 static void
4234 print_label_numbers(char *prefix, cksum_record_t *rec)
4235 {
4236 	printf("%s", prefix);
4237 	for (int i = 0; i < VDEV_LABELS; i++)
4238 		if (rec->labels[i] == B_TRUE)
4239 			printf("%d ", i);
4240 	printf("\n");
4241 }
4242 
4243 #define	MAX_UBERBLOCK_COUNT (VDEV_UBERBLOCK_RING >> UBERBLOCK_SHIFT)
4244 
4245 typedef struct zdb_label {
4246 	vdev_label_t label;
4247 	uint64_t label_offset;
4248 	nvlist_t *config_nv;
4249 	cksum_record_t *config;
4250 	cksum_record_t *uberblocks[MAX_UBERBLOCK_COUNT];
4251 	boolean_t header_printed;
4252 	boolean_t read_failed;
4253 	boolean_t cksum_valid;
4254 } zdb_label_t;
4255 
4256 static void
4257 print_label_header(zdb_label_t *label, int l)
4258 {
4259 
4260 	if (dump_opt['q'])
4261 		return;
4262 
4263 	if (label->header_printed == B_TRUE)
4264 		return;
4265 
4266 	(void) printf("------------------------------------\n");
4267 	(void) printf("LABEL %d %s\n", l,
4268 	    label->cksum_valid ? "" : "(Bad label cksum)");
4269 	(void) printf("------------------------------------\n");
4270 
4271 	label->header_printed = B_TRUE;
4272 }
4273 
4274 static void
4275 print_l2arc_header(void)
4276 {
4277 	(void) printf("------------------------------------\n");
4278 	(void) printf("L2ARC device header\n");
4279 	(void) printf("------------------------------------\n");
4280 }
4281 
4282 static void
4283 print_l2arc_log_blocks(void)
4284 {
4285 	(void) printf("------------------------------------\n");
4286 	(void) printf("L2ARC device log blocks\n");
4287 	(void) printf("------------------------------------\n");
4288 }
4289 
4290 static void
4291 dump_l2arc_log_entries(uint64_t log_entries,
4292     l2arc_log_ent_phys_t *le, uint64_t i)
4293 {
4294 	for (int j = 0; j < log_entries; j++) {
4295 		dva_t dva = le[j].le_dva;
4296 		(void) printf("lb[%4llu]\tle[%4d]\tDVA asize: %llu, "
4297 		    "vdev: %llu, offset: %llu\n",
4298 		    (u_longlong_t)i, j + 1,
4299 		    (u_longlong_t)DVA_GET_ASIZE(&dva),
4300 		    (u_longlong_t)DVA_GET_VDEV(&dva),
4301 		    (u_longlong_t)DVA_GET_OFFSET(&dva));
4302 		(void) printf("|\t\t\t\tbirth: %llu\n",
4303 		    (u_longlong_t)le[j].le_birth);
4304 		(void) printf("|\t\t\t\tlsize: %llu\n",
4305 		    (u_longlong_t)L2BLK_GET_LSIZE((&le[j])->le_prop));
4306 		(void) printf("|\t\t\t\tpsize: %llu\n",
4307 		    (u_longlong_t)L2BLK_GET_PSIZE((&le[j])->le_prop));
4308 		(void) printf("|\t\t\t\tcompr: %llu\n",
4309 		    (u_longlong_t)L2BLK_GET_COMPRESS((&le[j])->le_prop));
4310 		(void) printf("|\t\t\t\tcomplevel: %llu\n",
4311 		    (u_longlong_t)(&le[j])->le_complevel);
4312 		(void) printf("|\t\t\t\ttype: %llu\n",
4313 		    (u_longlong_t)L2BLK_GET_TYPE((&le[j])->le_prop));
4314 		(void) printf("|\t\t\t\tprotected: %llu\n",
4315 		    (u_longlong_t)L2BLK_GET_PROTECTED((&le[j])->le_prop));
4316 		(void) printf("|\t\t\t\tprefetch: %llu\n",
4317 		    (u_longlong_t)L2BLK_GET_PREFETCH((&le[j])->le_prop));
4318 		(void) printf("|\t\t\t\taddress: %llu\n",
4319 		    (u_longlong_t)le[j].le_daddr);
4320 		(void) printf("|\t\t\t\tARC state: %llu\n",
4321 		    (u_longlong_t)L2BLK_GET_STATE((&le[j])->le_prop));
4322 		(void) printf("|\n");
4323 	}
4324 	(void) printf("\n");
4325 }
4326 
4327 static void
4328 dump_l2arc_log_blkptr(l2arc_log_blkptr_t lbps)
4329 {
4330 	(void) printf("|\t\tdaddr: %llu\n", (u_longlong_t)lbps.lbp_daddr);
4331 	(void) printf("|\t\tpayload_asize: %llu\n",
4332 	    (u_longlong_t)lbps.lbp_payload_asize);
4333 	(void) printf("|\t\tpayload_start: %llu\n",
4334 	    (u_longlong_t)lbps.lbp_payload_start);
4335 	(void) printf("|\t\tlsize: %llu\n",
4336 	    (u_longlong_t)L2BLK_GET_LSIZE((&lbps)->lbp_prop));
4337 	(void) printf("|\t\tasize: %llu\n",
4338 	    (u_longlong_t)L2BLK_GET_PSIZE((&lbps)->lbp_prop));
4339 	(void) printf("|\t\tcompralgo: %llu\n",
4340 	    (u_longlong_t)L2BLK_GET_COMPRESS((&lbps)->lbp_prop));
4341 	(void) printf("|\t\tcksumalgo: %llu\n",
4342 	    (u_longlong_t)L2BLK_GET_CHECKSUM((&lbps)->lbp_prop));
4343 	(void) printf("|\n\n");
4344 }
4345 
4346 static void
4347 dump_l2arc_log_blocks(int fd, l2arc_dev_hdr_phys_t l2dhdr,
4348     l2arc_dev_hdr_phys_t *rebuild)
4349 {
4350 	l2arc_log_blk_phys_t this_lb;
4351 	uint64_t asize;
4352 	l2arc_log_blkptr_t lbps[2];
4353 	abd_t *abd;
4354 	zio_cksum_t cksum;
4355 	int failed = 0;
4356 	l2arc_dev_t dev;
4357 
4358 	if (!dump_opt['q'])
4359 		print_l2arc_log_blocks();
4360 	memcpy(lbps, l2dhdr.dh_start_lbps, sizeof (lbps));
4361 
4362 	dev.l2ad_evict = l2dhdr.dh_evict;
4363 	dev.l2ad_start = l2dhdr.dh_start;
4364 	dev.l2ad_end = l2dhdr.dh_end;
4365 
4366 	if (l2dhdr.dh_start_lbps[0].lbp_daddr == 0) {
4367 		/* no log blocks to read */
4368 		if (!dump_opt['q']) {
4369 			(void) printf("No log blocks to read\n");
4370 			(void) printf("\n");
4371 		}
4372 		return;
4373 	} else {
4374 		dev.l2ad_hand = lbps[0].lbp_daddr +
4375 		    L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
4376 	}
4377 
4378 	dev.l2ad_first = !!(l2dhdr.dh_flags & L2ARC_DEV_HDR_EVICT_FIRST);
4379 
4380 	for (;;) {
4381 		if (!l2arc_log_blkptr_valid(&dev, &lbps[0]))
4382 			break;
4383 
4384 		/* L2BLK_GET_PSIZE returns aligned size for log blocks */
4385 		asize = L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
4386 		if (pread64(fd, &this_lb, asize, lbps[0].lbp_daddr) != asize) {
4387 			if (!dump_opt['q']) {
4388 				(void) printf("Error while reading next log "
4389 				    "block\n\n");
4390 			}
4391 			break;
4392 		}
4393 
4394 		fletcher_4_native_varsize(&this_lb, asize, &cksum);
4395 		if (!ZIO_CHECKSUM_EQUAL(cksum, lbps[0].lbp_cksum)) {
4396 			failed++;
4397 			if (!dump_opt['q']) {
4398 				(void) printf("Invalid cksum\n");
4399 				dump_l2arc_log_blkptr(lbps[0]);
4400 			}
4401 			break;
4402 		}
4403 
4404 		switch (L2BLK_GET_COMPRESS((&lbps[0])->lbp_prop)) {
4405 		case ZIO_COMPRESS_OFF:
4406 			break;
4407 		default:
4408 			abd = abd_alloc_for_io(asize, B_TRUE);
4409 			abd_copy_from_buf_off(abd, &this_lb, 0, asize);
4410 			zio_decompress_data(L2BLK_GET_COMPRESS(
4411 			    (&lbps[0])->lbp_prop), abd, &this_lb,
4412 			    asize, sizeof (this_lb), NULL);
4413 			abd_free(abd);
4414 			break;
4415 		}
4416 
4417 		if (this_lb.lb_magic == BSWAP_64(L2ARC_LOG_BLK_MAGIC))
4418 			byteswap_uint64_array(&this_lb, sizeof (this_lb));
4419 		if (this_lb.lb_magic != L2ARC_LOG_BLK_MAGIC) {
4420 			if (!dump_opt['q'])
4421 				(void) printf("Invalid log block magic\n\n");
4422 			break;
4423 		}
4424 
4425 		rebuild->dh_lb_count++;
4426 		rebuild->dh_lb_asize += asize;
4427 		if (dump_opt['l'] > 1 && !dump_opt['q']) {
4428 			(void) printf("lb[%4llu]\tmagic: %llu\n",
4429 			    (u_longlong_t)rebuild->dh_lb_count,
4430 			    (u_longlong_t)this_lb.lb_magic);
4431 			dump_l2arc_log_blkptr(lbps[0]);
4432 		}
4433 
4434 		if (dump_opt['l'] > 2 && !dump_opt['q'])
4435 			dump_l2arc_log_entries(l2dhdr.dh_log_entries,
4436 			    this_lb.lb_entries,
4437 			    rebuild->dh_lb_count);
4438 
4439 		if (l2arc_range_check_overlap(lbps[1].lbp_payload_start,
4440 		    lbps[0].lbp_payload_start, dev.l2ad_evict) &&
4441 		    !dev.l2ad_first)
4442 			break;
4443 
4444 		lbps[0] = lbps[1];
4445 		lbps[1] = this_lb.lb_prev_lbp;
4446 	}
4447 
4448 	if (!dump_opt['q']) {
4449 		(void) printf("log_blk_count:\t %llu with valid cksum\n",
4450 		    (u_longlong_t)rebuild->dh_lb_count);
4451 		(void) printf("\t\t %d with invalid cksum\n", failed);
4452 		(void) printf("log_blk_asize:\t %llu\n\n",
4453 		    (u_longlong_t)rebuild->dh_lb_asize);
4454 	}
4455 }
4456 
4457 static int
4458 dump_l2arc_header(int fd)
4459 {
4460 	l2arc_dev_hdr_phys_t l2dhdr = {0}, rebuild = {0};
4461 	int error = B_FALSE;
4462 
4463 	if (pread64(fd, &l2dhdr, sizeof (l2dhdr),
4464 	    VDEV_LABEL_START_SIZE) != sizeof (l2dhdr)) {
4465 		error = B_TRUE;
4466 	} else {
4467 		if (l2dhdr.dh_magic == BSWAP_64(L2ARC_DEV_HDR_MAGIC))
4468 			byteswap_uint64_array(&l2dhdr, sizeof (l2dhdr));
4469 
4470 		if (l2dhdr.dh_magic != L2ARC_DEV_HDR_MAGIC)
4471 			error = B_TRUE;
4472 	}
4473 
4474 	if (error) {
4475 		(void) printf("L2ARC device header not found\n\n");
4476 		/* Do not return an error here for backward compatibility */
4477 		return (0);
4478 	} else if (!dump_opt['q']) {
4479 		print_l2arc_header();
4480 
4481 		(void) printf("    magic: %llu\n",
4482 		    (u_longlong_t)l2dhdr.dh_magic);
4483 		(void) printf("    version: %llu\n",
4484 		    (u_longlong_t)l2dhdr.dh_version);
4485 		(void) printf("    pool_guid: %llu\n",
4486 		    (u_longlong_t)l2dhdr.dh_spa_guid);
4487 		(void) printf("    flags: %llu\n",
4488 		    (u_longlong_t)l2dhdr.dh_flags);
4489 		(void) printf("    start_lbps[0]: %llu\n",
4490 		    (u_longlong_t)
4491 		    l2dhdr.dh_start_lbps[0].lbp_daddr);
4492 		(void) printf("    start_lbps[1]: %llu\n",
4493 		    (u_longlong_t)
4494 		    l2dhdr.dh_start_lbps[1].lbp_daddr);
4495 		(void) printf("    log_blk_ent: %llu\n",
4496 		    (u_longlong_t)l2dhdr.dh_log_entries);
4497 		(void) printf("    start: %llu\n",
4498 		    (u_longlong_t)l2dhdr.dh_start);
4499 		(void) printf("    end: %llu\n",
4500 		    (u_longlong_t)l2dhdr.dh_end);
4501 		(void) printf("    evict: %llu\n",
4502 		    (u_longlong_t)l2dhdr.dh_evict);
4503 		(void) printf("    lb_asize_refcount: %llu\n",
4504 		    (u_longlong_t)l2dhdr.dh_lb_asize);
4505 		(void) printf("    lb_count_refcount: %llu\n",
4506 		    (u_longlong_t)l2dhdr.dh_lb_count);
4507 		(void) printf("    trim_action_time: %llu\n",
4508 		    (u_longlong_t)l2dhdr.dh_trim_action_time);
4509 		(void) printf("    trim_state: %llu\n\n",
4510 		    (u_longlong_t)l2dhdr.dh_trim_state);
4511 	}
4512 
4513 	dump_l2arc_log_blocks(fd, l2dhdr, &rebuild);
4514 	/*
4515 	 * The total aligned size of log blocks and the number of log blocks
4516 	 * reported in the header of the device may be less than what zdb
4517 	 * reports by dump_l2arc_log_blocks() which emulates l2arc_rebuild().
4518 	 * This happens because dump_l2arc_log_blocks() lacks the memory
4519 	 * pressure valve that l2arc_rebuild() has. Thus, if we are on a system
4520 	 * with low memory, l2arc_rebuild will exit prematurely and dh_lb_asize
4521 	 * and dh_lb_count will be lower to begin with than what exists on the
4522 	 * device. This is normal and zdb should not exit with an error. The
4523 	 * opposite case should never happen though, the values reported in the
4524 	 * header should never be higher than what dump_l2arc_log_blocks() and
4525 	 * l2arc_rebuild() report. If this happens there is a leak in the
4526 	 * accounting of log blocks.
4527 	 */
4528 	if (l2dhdr.dh_lb_asize > rebuild.dh_lb_asize ||
4529 	    l2dhdr.dh_lb_count > rebuild.dh_lb_count)
4530 		return (1);
4531 
4532 	return (0);
4533 }
4534 
4535 static void
4536 dump_config_from_label(zdb_label_t *label, size_t buflen, int l)
4537 {
4538 	if (dump_opt['q'])
4539 		return;
4540 
4541 	if ((dump_opt['l'] < 3) && (first_label(label->config) != l))
4542 		return;
4543 
4544 	print_label_header(label, l);
4545 	dump_nvlist(label->config_nv, 4);
4546 	print_label_numbers("    labels = ", label->config);
4547 
4548 	if (dump_opt['l'] >= 2)
4549 		dump_nvlist_stats(label->config_nv, buflen);
4550 }
4551 
4552 #define	ZDB_MAX_UB_HEADER_SIZE 32
4553 
4554 static void
4555 dump_label_uberblocks(zdb_label_t *label, uint64_t ashift, int label_num)
4556 {
4557 
4558 	vdev_t vd;
4559 	char header[ZDB_MAX_UB_HEADER_SIZE];
4560 
4561 	vd.vdev_ashift = ashift;
4562 	vd.vdev_top = &vd;
4563 
4564 	for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
4565 		uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
4566 		uberblock_t *ub = (void *)((char *)&label->label + uoff);
4567 		cksum_record_t *rec = label->uberblocks[i];
4568 
4569 		if (rec == NULL) {
4570 			if (dump_opt['u'] >= 2) {
4571 				print_label_header(label, label_num);
4572 				(void) printf("    Uberblock[%d] invalid\n", i);
4573 			}
4574 			continue;
4575 		}
4576 
4577 		if ((dump_opt['u'] < 3) && (first_label(rec) != label_num))
4578 			continue;
4579 
4580 		if ((dump_opt['u'] < 4) &&
4581 		    (ub->ub_mmp_magic == MMP_MAGIC) && ub->ub_mmp_delay &&
4582 		    (i >= VDEV_UBERBLOCK_COUNT(&vd) - MMP_BLOCKS_PER_LABEL))
4583 			continue;
4584 
4585 		print_label_header(label, label_num);
4586 		(void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
4587 		    "    Uberblock[%d]\n", i);
4588 		dump_uberblock(ub, header, "");
4589 		print_label_numbers("        labels = ", rec);
4590 	}
4591 }
4592 
4593 static char curpath[PATH_MAX];
4594 
4595 /*
4596  * Iterate through the path components, recursively passing
4597  * current one's obj and remaining path until we find the obj
4598  * for the last one.
4599  */
4600 static int
4601 dump_path_impl(objset_t *os, uint64_t obj, char *name, uint64_t *retobj)
4602 {
4603 	int err;
4604 	boolean_t header = B_TRUE;
4605 	uint64_t child_obj;
4606 	char *s;
4607 	dmu_buf_t *db;
4608 	dmu_object_info_t doi;
4609 
4610 	if ((s = strchr(name, '/')) != NULL)
4611 		*s = '\0';
4612 	err = zap_lookup(os, obj, name, 8, 1, &child_obj);
4613 
4614 	(void) strlcat(curpath, name, sizeof (curpath));
4615 
4616 	if (err != 0) {
4617 		(void) fprintf(stderr, "failed to lookup %s: %s\n",
4618 		    curpath, strerror(err));
4619 		return (err);
4620 	}
4621 
4622 	child_obj = ZFS_DIRENT_OBJ(child_obj);
4623 	err = sa_buf_hold(os, child_obj, FTAG, &db);
4624 	if (err != 0) {
4625 		(void) fprintf(stderr,
4626 		    "failed to get SA dbuf for obj %llu: %s\n",
4627 		    (u_longlong_t)child_obj, strerror(err));
4628 		return (EINVAL);
4629 	}
4630 	dmu_object_info_from_db(db, &doi);
4631 	sa_buf_rele(db, FTAG);
4632 
4633 	if (doi.doi_bonus_type != DMU_OT_SA &&
4634 	    doi.doi_bonus_type != DMU_OT_ZNODE) {
4635 		(void) fprintf(stderr, "invalid bonus type %d for obj %llu\n",
4636 		    doi.doi_bonus_type, (u_longlong_t)child_obj);
4637 		return (EINVAL);
4638 	}
4639 
4640 	if (dump_opt['v'] > 6) {
4641 		(void) printf("obj=%llu %s type=%d bonustype=%d\n",
4642 		    (u_longlong_t)child_obj, curpath, doi.doi_type,
4643 		    doi.doi_bonus_type);
4644 	}
4645 
4646 	(void) strlcat(curpath, "/", sizeof (curpath));
4647 
4648 	switch (doi.doi_type) {
4649 	case DMU_OT_DIRECTORY_CONTENTS:
4650 		if (s != NULL && *(s + 1) != '\0')
4651 			return (dump_path_impl(os, child_obj, s + 1, retobj));
4652 		zfs_fallthrough;
4653 	case DMU_OT_PLAIN_FILE_CONTENTS:
4654 		if (retobj != NULL) {
4655 			*retobj = child_obj;
4656 		} else {
4657 			dump_object(os, child_obj, dump_opt['v'], &header,
4658 			    NULL, 0);
4659 		}
4660 		return (0);
4661 	default:
4662 		(void) fprintf(stderr, "object %llu has non-file/directory "
4663 		    "type %d\n", (u_longlong_t)obj, doi.doi_type);
4664 		break;
4665 	}
4666 
4667 	return (EINVAL);
4668 }
4669 
4670 /*
4671  * Dump the blocks for the object specified by path inside the dataset.
4672  */
4673 static int
4674 dump_path(char *ds, char *path, uint64_t *retobj)
4675 {
4676 	int err;
4677 	objset_t *os;
4678 	uint64_t root_obj;
4679 
4680 	err = open_objset(ds, FTAG, &os);
4681 	if (err != 0)
4682 		return (err);
4683 
4684 	err = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1, &root_obj);
4685 	if (err != 0) {
4686 		(void) fprintf(stderr, "can't lookup root znode: %s\n",
4687 		    strerror(err));
4688 		close_objset(os, FTAG);
4689 		return (EINVAL);
4690 	}
4691 
4692 	(void) snprintf(curpath, sizeof (curpath), "dataset=%s path=/", ds);
4693 
4694 	err = dump_path_impl(os, root_obj, path, retobj);
4695 
4696 	close_objset(os, FTAG);
4697 	return (err);
4698 }
4699 
4700 static int
4701 zdb_copy_object(objset_t *os, uint64_t srcobj, char *destfile)
4702 {
4703 	int err = 0;
4704 	uint64_t size, readsize, oursize, offset;
4705 	ssize_t writesize;
4706 	sa_handle_t *hdl;
4707 
4708 	(void) printf("Copying object %" PRIu64 " to file %s\n", srcobj,
4709 	    destfile);
4710 
4711 	VERIFY3P(os, ==, sa_os);
4712 	if ((err = sa_handle_get(os, srcobj, NULL, SA_HDL_PRIVATE, &hdl))) {
4713 		(void) printf("Failed to get handle for SA znode\n");
4714 		return (err);
4715 	}
4716 	if ((err = sa_lookup(hdl, sa_attr_table[ZPL_SIZE], &size, 8))) {
4717 		(void) sa_handle_destroy(hdl);
4718 		return (err);
4719 	}
4720 	(void) sa_handle_destroy(hdl);
4721 
4722 	(void) printf("Object %" PRIu64 " is %" PRIu64 " bytes\n", srcobj,
4723 	    size);
4724 	if (size == 0) {
4725 		return (EINVAL);
4726 	}
4727 
4728 	int fd = open(destfile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
4729 	/*
4730 	 * We cap the size at 1 mebibyte here to prevent
4731 	 * allocation failures and nigh-infinite printing if the
4732 	 * object is extremely large.
4733 	 */
4734 	oursize = MIN(size, 1 << 20);
4735 	offset = 0;
4736 	char *buf = kmem_alloc(oursize, KM_NOSLEEP);
4737 	if (buf == NULL) {
4738 		return (ENOMEM);
4739 	}
4740 
4741 	while (offset < size) {
4742 		readsize = MIN(size - offset, 1 << 20);
4743 		err = dmu_read(os, srcobj, offset, readsize, buf, 0);
4744 		if (err != 0) {
4745 			(void) printf("got error %u from dmu_read\n", err);
4746 			kmem_free(buf, oursize);
4747 			return (err);
4748 		}
4749 		if (dump_opt['v'] > 3) {
4750 			(void) printf("Read offset=%" PRIu64 " size=%" PRIu64
4751 			    " error=%d\n", offset, readsize, err);
4752 		}
4753 
4754 		writesize = write(fd, buf, readsize);
4755 		if (writesize < 0) {
4756 			err = errno;
4757 			break;
4758 		} else if (writesize != readsize) {
4759 			/* Incomplete write */
4760 			(void) fprintf(stderr, "Short write, only wrote %llu of"
4761 			    " %" PRIu64 " bytes, exiting...\n",
4762 			    (u_longlong_t)writesize, readsize);
4763 			break;
4764 		}
4765 
4766 		offset += readsize;
4767 	}
4768 
4769 	(void) close(fd);
4770 
4771 	if (buf != NULL)
4772 		kmem_free(buf, oursize);
4773 
4774 	return (err);
4775 }
4776 
4777 static boolean_t
4778 label_cksum_valid(vdev_label_t *label, uint64_t offset)
4779 {
4780 	zio_checksum_info_t *ci = &zio_checksum_table[ZIO_CHECKSUM_LABEL];
4781 	zio_cksum_t expected_cksum;
4782 	zio_cksum_t actual_cksum;
4783 	zio_cksum_t verifier;
4784 	zio_eck_t *eck;
4785 	int byteswap;
4786 
4787 	void *data = (char *)label + offsetof(vdev_label_t, vl_vdev_phys);
4788 	eck = (zio_eck_t *)((char *)(data) + VDEV_PHYS_SIZE) - 1;
4789 
4790 	offset += offsetof(vdev_label_t, vl_vdev_phys);
4791 	ZIO_SET_CHECKSUM(&verifier, offset, 0, 0, 0);
4792 
4793 	byteswap = (eck->zec_magic == BSWAP_64(ZEC_MAGIC));
4794 	if (byteswap)
4795 		byteswap_uint64_array(&verifier, sizeof (zio_cksum_t));
4796 
4797 	expected_cksum = eck->zec_cksum;
4798 	eck->zec_cksum = verifier;
4799 
4800 	abd_t *abd = abd_get_from_buf(data, VDEV_PHYS_SIZE);
4801 	ci->ci_func[byteswap](abd, VDEV_PHYS_SIZE, NULL, &actual_cksum);
4802 	abd_free(abd);
4803 
4804 	if (byteswap)
4805 		byteswap_uint64_array(&expected_cksum, sizeof (zio_cksum_t));
4806 
4807 	if (ZIO_CHECKSUM_EQUAL(actual_cksum, expected_cksum))
4808 		return (B_TRUE);
4809 
4810 	return (B_FALSE);
4811 }
4812 
4813 static int
4814 dump_label(const char *dev)
4815 {
4816 	char path[MAXPATHLEN];
4817 	zdb_label_t labels[VDEV_LABELS] = {{{{0}}}};
4818 	uint64_t psize, ashift, l2cache;
4819 	struct stat64 statbuf;
4820 	boolean_t config_found = B_FALSE;
4821 	boolean_t error = B_FALSE;
4822 	boolean_t read_l2arc_header = B_FALSE;
4823 	avl_tree_t config_tree;
4824 	avl_tree_t uberblock_tree;
4825 	void *node, *cookie;
4826 	int fd;
4827 
4828 	/*
4829 	 * Check if we were given absolute path and use it as is.
4830 	 * Otherwise if the provided vdev name doesn't point to a file,
4831 	 * try prepending expected disk paths and partition numbers.
4832 	 */
4833 	(void) strlcpy(path, dev, sizeof (path));
4834 	if (dev[0] != '/' && stat64(path, &statbuf) != 0) {
4835 		int error;
4836 
4837 		error = zfs_resolve_shortname(dev, path, MAXPATHLEN);
4838 		if (error == 0 && zfs_dev_is_whole_disk(path)) {
4839 			if (zfs_append_partition(path, MAXPATHLEN) == -1)
4840 				error = ENOENT;
4841 		}
4842 
4843 		if (error || (stat64(path, &statbuf) != 0)) {
4844 			(void) printf("failed to find device %s, try "
4845 			    "specifying absolute path instead\n", dev);
4846 			return (1);
4847 		}
4848 	}
4849 
4850 	if ((fd = open64(path, O_RDONLY)) < 0) {
4851 		(void) printf("cannot open '%s': %s\n", path, strerror(errno));
4852 		exit(1);
4853 	}
4854 
4855 	if (fstat64_blk(fd, &statbuf) != 0) {
4856 		(void) printf("failed to stat '%s': %s\n", path,
4857 		    strerror(errno));
4858 		(void) close(fd);
4859 		exit(1);
4860 	}
4861 
4862 	if (S_ISBLK(statbuf.st_mode) && zfs_dev_flush(fd) != 0)
4863 		(void) printf("failed to invalidate cache '%s' : %s\n", path,
4864 		    strerror(errno));
4865 
4866 	avl_create(&config_tree, cksum_record_compare,
4867 	    sizeof (cksum_record_t), offsetof(cksum_record_t, link));
4868 	avl_create(&uberblock_tree, cksum_record_compare,
4869 	    sizeof (cksum_record_t), offsetof(cksum_record_t, link));
4870 
4871 	psize = statbuf.st_size;
4872 	psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
4873 	ashift = SPA_MINBLOCKSHIFT;
4874 
4875 	/*
4876 	 * 1. Read the label from disk
4877 	 * 2. Verify label cksum
4878 	 * 3. Unpack the configuration and insert in config tree.
4879 	 * 4. Traverse all uberblocks and insert in uberblock tree.
4880 	 */
4881 	for (int l = 0; l < VDEV_LABELS; l++) {
4882 		zdb_label_t *label = &labels[l];
4883 		char *buf = label->label.vl_vdev_phys.vp_nvlist;
4884 		size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
4885 		nvlist_t *config;
4886 		cksum_record_t *rec;
4887 		zio_cksum_t cksum;
4888 		vdev_t vd;
4889 
4890 		label->label_offset = vdev_label_offset(psize, l, 0);
4891 
4892 		if (pread64(fd, &label->label, sizeof (label->label),
4893 		    label->label_offset) != sizeof (label->label)) {
4894 			if (!dump_opt['q'])
4895 				(void) printf("failed to read label %d\n", l);
4896 			label->read_failed = B_TRUE;
4897 			error = B_TRUE;
4898 			continue;
4899 		}
4900 
4901 		label->read_failed = B_FALSE;
4902 		label->cksum_valid = label_cksum_valid(&label->label,
4903 		    label->label_offset);
4904 
4905 		if (nvlist_unpack(buf, buflen, &config, 0) == 0) {
4906 			nvlist_t *vdev_tree = NULL;
4907 			size_t size;
4908 
4909 			if ((nvlist_lookup_nvlist(config,
4910 			    ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
4911 			    (nvlist_lookup_uint64(vdev_tree,
4912 			    ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
4913 				ashift = SPA_MINBLOCKSHIFT;
4914 
4915 			if (nvlist_size(config, &size, NV_ENCODE_XDR) != 0)
4916 				size = buflen;
4917 
4918 			/* If the device is a cache device clear the header. */
4919 			if (!read_l2arc_header) {
4920 				if (nvlist_lookup_uint64(config,
4921 				    ZPOOL_CONFIG_POOL_STATE, &l2cache) == 0 &&
4922 				    l2cache == POOL_STATE_L2CACHE) {
4923 					read_l2arc_header = B_TRUE;
4924 				}
4925 			}
4926 
4927 			fletcher_4_native_varsize(buf, size, &cksum);
4928 			rec = cksum_record_insert(&config_tree, &cksum, l);
4929 
4930 			label->config = rec;
4931 			label->config_nv = config;
4932 			config_found = B_TRUE;
4933 		} else {
4934 			error = B_TRUE;
4935 		}
4936 
4937 		vd.vdev_ashift = ashift;
4938 		vd.vdev_top = &vd;
4939 
4940 		for (int i = 0; i < VDEV_UBERBLOCK_COUNT(&vd); i++) {
4941 			uint64_t uoff = VDEV_UBERBLOCK_OFFSET(&vd, i);
4942 			uberblock_t *ub = (void *)((char *)label + uoff);
4943 
4944 			if (uberblock_verify(ub))
4945 				continue;
4946 
4947 			fletcher_4_native_varsize(ub, sizeof (*ub), &cksum);
4948 			rec = cksum_record_insert(&uberblock_tree, &cksum, l);
4949 
4950 			label->uberblocks[i] = rec;
4951 		}
4952 	}
4953 
4954 	/*
4955 	 * Dump the label and uberblocks.
4956 	 */
4957 	for (int l = 0; l < VDEV_LABELS; l++) {
4958 		zdb_label_t *label = &labels[l];
4959 		size_t buflen = sizeof (label->label.vl_vdev_phys.vp_nvlist);
4960 
4961 		if (label->read_failed == B_TRUE)
4962 			continue;
4963 
4964 		if (label->config_nv) {
4965 			dump_config_from_label(label, buflen, l);
4966 		} else {
4967 			if (!dump_opt['q'])
4968 				(void) printf("failed to unpack label %d\n", l);
4969 		}
4970 
4971 		if (dump_opt['u'])
4972 			dump_label_uberblocks(label, ashift, l);
4973 
4974 		nvlist_free(label->config_nv);
4975 	}
4976 
4977 	/*
4978 	 * Dump the L2ARC header, if existent.
4979 	 */
4980 	if (read_l2arc_header)
4981 		error |= dump_l2arc_header(fd);
4982 
4983 	cookie = NULL;
4984 	while ((node = avl_destroy_nodes(&config_tree, &cookie)) != NULL)
4985 		umem_free(node, sizeof (cksum_record_t));
4986 
4987 	cookie = NULL;
4988 	while ((node = avl_destroy_nodes(&uberblock_tree, &cookie)) != NULL)
4989 		umem_free(node, sizeof (cksum_record_t));
4990 
4991 	avl_destroy(&config_tree);
4992 	avl_destroy(&uberblock_tree);
4993 
4994 	(void) close(fd);
4995 
4996 	return (config_found == B_FALSE ? 2 :
4997 	    (error == B_TRUE ? 1 : 0));
4998 }
4999 
5000 static uint64_t dataset_feature_count[SPA_FEATURES];
5001 static uint64_t global_feature_count[SPA_FEATURES];
5002 static uint64_t remap_deadlist_count = 0;
5003 
5004 static int
5005 dump_one_objset(const char *dsname, void *arg)
5006 {
5007 	(void) arg;
5008 	int error;
5009 	objset_t *os;
5010 	spa_feature_t f;
5011 
5012 	error = open_objset(dsname, FTAG, &os);
5013 	if (error != 0)
5014 		return (0);
5015 
5016 	for (f = 0; f < SPA_FEATURES; f++) {
5017 		if (!dsl_dataset_feature_is_active(dmu_objset_ds(os), f))
5018 			continue;
5019 		ASSERT(spa_feature_table[f].fi_flags &
5020 		    ZFEATURE_FLAG_PER_DATASET);
5021 		dataset_feature_count[f]++;
5022 	}
5023 
5024 	if (dsl_dataset_remap_deadlist_exists(dmu_objset_ds(os))) {
5025 		remap_deadlist_count++;
5026 	}
5027 
5028 	for (dsl_bookmark_node_t *dbn =
5029 	    avl_first(&dmu_objset_ds(os)->ds_bookmarks); dbn != NULL;
5030 	    dbn = AVL_NEXT(&dmu_objset_ds(os)->ds_bookmarks, dbn)) {
5031 		mos_obj_refd(dbn->dbn_phys.zbm_redaction_obj);
5032 		if (dbn->dbn_phys.zbm_redaction_obj != 0)
5033 			global_feature_count[SPA_FEATURE_REDACTION_BOOKMARKS]++;
5034 		if (dbn->dbn_phys.zbm_flags & ZBM_FLAG_HAS_FBN)
5035 			global_feature_count[SPA_FEATURE_BOOKMARK_WRITTEN]++;
5036 	}
5037 
5038 	if (dsl_deadlist_is_open(&dmu_objset_ds(os)->ds_dir->dd_livelist) &&
5039 	    !dmu_objset_is_snapshot(os)) {
5040 		global_feature_count[SPA_FEATURE_LIVELIST]++;
5041 	}
5042 
5043 	dump_objset(os);
5044 	close_objset(os, FTAG);
5045 	fuid_table_destroy();
5046 	return (0);
5047 }
5048 
5049 /*
5050  * Block statistics.
5051  */
5052 #define	PSIZE_HISTO_SIZE (SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 2)
5053 typedef struct zdb_blkstats {
5054 	uint64_t zb_asize;
5055 	uint64_t zb_lsize;
5056 	uint64_t zb_psize;
5057 	uint64_t zb_count;
5058 	uint64_t zb_gangs;
5059 	uint64_t zb_ditto_samevdev;
5060 	uint64_t zb_ditto_same_ms;
5061 	uint64_t zb_psize_histogram[PSIZE_HISTO_SIZE];
5062 } zdb_blkstats_t;
5063 
5064 /*
5065  * Extended object types to report deferred frees and dedup auto-ditto blocks.
5066  */
5067 #define	ZDB_OT_DEFERRED	(DMU_OT_NUMTYPES + 0)
5068 #define	ZDB_OT_DITTO	(DMU_OT_NUMTYPES + 1)
5069 #define	ZDB_OT_OTHER	(DMU_OT_NUMTYPES + 2)
5070 #define	ZDB_OT_TOTAL	(DMU_OT_NUMTYPES + 3)
5071 
5072 static const char *zdb_ot_extname[] = {
5073 	"deferred free",
5074 	"dedup ditto",
5075 	"other",
5076 	"Total",
5077 };
5078 
5079 #define	ZB_TOTAL	DN_MAX_LEVELS
5080 #define	SPA_MAX_FOR_16M	(SPA_MAXBLOCKSHIFT+1)
5081 
5082 typedef struct zdb_cb {
5083 	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
5084 	uint64_t	zcb_removing_size;
5085 	uint64_t	zcb_checkpoint_size;
5086 	uint64_t	zcb_dedup_asize;
5087 	uint64_t	zcb_dedup_blocks;
5088 	uint64_t	zcb_psize_count[SPA_MAX_FOR_16M];
5089 	uint64_t	zcb_lsize_count[SPA_MAX_FOR_16M];
5090 	uint64_t	zcb_asize_count[SPA_MAX_FOR_16M];
5091 	uint64_t	zcb_psize_len[SPA_MAX_FOR_16M];
5092 	uint64_t	zcb_lsize_len[SPA_MAX_FOR_16M];
5093 	uint64_t	zcb_asize_len[SPA_MAX_FOR_16M];
5094 	uint64_t	zcb_psize_total;
5095 	uint64_t	zcb_lsize_total;
5096 	uint64_t	zcb_asize_total;
5097 	uint64_t	zcb_embedded_blocks[NUM_BP_EMBEDDED_TYPES];
5098 	uint64_t	zcb_embedded_histogram[NUM_BP_EMBEDDED_TYPES]
5099 	    [BPE_PAYLOAD_SIZE + 1];
5100 	uint64_t	zcb_start;
5101 	hrtime_t	zcb_lastprint;
5102 	uint64_t	zcb_totalasize;
5103 	uint64_t	zcb_errors[256];
5104 	int		zcb_readfails;
5105 	int		zcb_haderrors;
5106 	spa_t		*zcb_spa;
5107 	uint32_t	**zcb_vd_obsolete_counts;
5108 } zdb_cb_t;
5109 
5110 /* test if two DVA offsets from same vdev are within the same metaslab */
5111 static boolean_t
5112 same_metaslab(spa_t *spa, uint64_t vdev, uint64_t off1, uint64_t off2)
5113 {
5114 	vdev_t *vd = vdev_lookup_top(spa, vdev);
5115 	uint64_t ms_shift = vd->vdev_ms_shift;
5116 
5117 	return ((off1 >> ms_shift) == (off2 >> ms_shift));
5118 }
5119 
5120 /*
5121  * Used to simplify reporting of the histogram data.
5122  */
5123 typedef struct one_histo {
5124 	char *name;
5125 	uint64_t *count;
5126 	uint64_t *len;
5127 	uint64_t cumulative;
5128 } one_histo_t;
5129 
5130 /*
5131  * The number of separate histograms processed for psize, lsize and asize.
5132  */
5133 #define	NUM_HISTO 3
5134 
5135 /*
5136  * This routine will create a fixed column size output of three different
5137  * histograms showing by blocksize of 512 - 2^ SPA_MAX_FOR_16M
5138  * the count, length and cumulative length of the psize, lsize and
5139  * asize blocks.
5140  *
5141  * All three types of blocks are listed on a single line
5142  *
5143  * By default the table is printed in nicenumber format (e.g. 123K) but
5144  * if the '-P' parameter is specified then the full raw number (parseable)
5145  * is printed out.
5146  */
5147 static void
5148 dump_size_histograms(zdb_cb_t *zcb)
5149 {
5150 	/*
5151 	 * A temporary buffer that allows us to convert a number into
5152 	 * a string using zdb_nicenumber to allow either raw or human
5153 	 * readable numbers to be output.
5154 	 */
5155 	char numbuf[32];
5156 
5157 	/*
5158 	 * Define titles which are used in the headers of the tables
5159 	 * printed by this routine.
5160 	 */
5161 	const char blocksize_title1[] = "block";
5162 	const char blocksize_title2[] = "size";
5163 	const char count_title[] = "Count";
5164 	const char length_title[] = "Size";
5165 	const char cumulative_title[] = "Cum.";
5166 
5167 	/*
5168 	 * Setup the histogram arrays (psize, lsize, and asize).
5169 	 */
5170 	one_histo_t parm_histo[NUM_HISTO];
5171 
5172 	parm_histo[0].name = "psize";
5173 	parm_histo[0].count = zcb->zcb_psize_count;
5174 	parm_histo[0].len = zcb->zcb_psize_len;
5175 	parm_histo[0].cumulative = 0;
5176 
5177 	parm_histo[1].name = "lsize";
5178 	parm_histo[1].count = zcb->zcb_lsize_count;
5179 	parm_histo[1].len = zcb->zcb_lsize_len;
5180 	parm_histo[1].cumulative = 0;
5181 
5182 	parm_histo[2].name = "asize";
5183 	parm_histo[2].count = zcb->zcb_asize_count;
5184 	parm_histo[2].len = zcb->zcb_asize_len;
5185 	parm_histo[2].cumulative = 0;
5186 
5187 
5188 	(void) printf("\nBlock Size Histogram\n");
5189 	/*
5190 	 * Print the first line titles
5191 	 */
5192 	if (dump_opt['P'])
5193 		(void) printf("\n%s\t", blocksize_title1);
5194 	else
5195 		(void) printf("\n%7s   ", blocksize_title1);
5196 
5197 	for (int j = 0; j < NUM_HISTO; j++) {
5198 		if (dump_opt['P']) {
5199 			if (j < NUM_HISTO - 1) {
5200 				(void) printf("%s\t\t\t", parm_histo[j].name);
5201 			} else {
5202 				/* Don't print trailing spaces */
5203 				(void) printf("  %s", parm_histo[j].name);
5204 			}
5205 		} else {
5206 			if (j < NUM_HISTO - 1) {
5207 				/* Left aligned strings in the output */
5208 				(void) printf("%-7s              ",
5209 				    parm_histo[j].name);
5210 			} else {
5211 				/* Don't print trailing spaces */
5212 				(void) printf("%s", parm_histo[j].name);
5213 			}
5214 		}
5215 	}
5216 	(void) printf("\n");
5217 
5218 	/*
5219 	 * Print the second line titles
5220 	 */
5221 	if (dump_opt['P']) {
5222 		(void) printf("%s\t", blocksize_title2);
5223 	} else {
5224 		(void) printf("%7s ", blocksize_title2);
5225 	}
5226 
5227 	for (int i = 0; i < NUM_HISTO; i++) {
5228 		if (dump_opt['P']) {
5229 			(void) printf("%s\t%s\t%s\t",
5230 			    count_title, length_title, cumulative_title);
5231 		} else {
5232 			(void) printf("%7s%7s%7s",
5233 			    count_title, length_title, cumulative_title);
5234 		}
5235 	}
5236 	(void) printf("\n");
5237 
5238 	/*
5239 	 * Print the rows
5240 	 */
5241 	for (int i = SPA_MINBLOCKSHIFT; i < SPA_MAX_FOR_16M; i++) {
5242 
5243 		/*
5244 		 * Print the first column showing the blocksize
5245 		 */
5246 		zdb_nicenum((1ULL << i), numbuf, sizeof (numbuf));
5247 
5248 		if (dump_opt['P']) {
5249 			printf("%s", numbuf);
5250 		} else {
5251 			printf("%7s:", numbuf);
5252 		}
5253 
5254 		/*
5255 		 * Print the remaining set of 3 columns per size:
5256 		 * for psize, lsize and asize
5257 		 */
5258 		for (int j = 0; j < NUM_HISTO; j++) {
5259 			parm_histo[j].cumulative += parm_histo[j].len[i];
5260 
5261 			zdb_nicenum(parm_histo[j].count[i],
5262 			    numbuf, sizeof (numbuf));
5263 			if (dump_opt['P'])
5264 				(void) printf("\t%s", numbuf);
5265 			else
5266 				(void) printf("%7s", numbuf);
5267 
5268 			zdb_nicenum(parm_histo[j].len[i],
5269 			    numbuf, sizeof (numbuf));
5270 			if (dump_opt['P'])
5271 				(void) printf("\t%s", numbuf);
5272 			else
5273 				(void) printf("%7s", numbuf);
5274 
5275 			zdb_nicenum(parm_histo[j].cumulative,
5276 			    numbuf, sizeof (numbuf));
5277 			if (dump_opt['P'])
5278 				(void) printf("\t%s", numbuf);
5279 			else
5280 				(void) printf("%7s", numbuf);
5281 		}
5282 		(void) printf("\n");
5283 	}
5284 }
5285 
5286 static void
5287 zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
5288     dmu_object_type_t type)
5289 {
5290 	uint64_t refcnt = 0;
5291 	int i;
5292 
5293 	ASSERT(type < ZDB_OT_TOTAL);
5294 
5295 	if (zilog && zil_bp_tree_add(zilog, bp) != 0)
5296 		return;
5297 
5298 	spa_config_enter(zcb->zcb_spa, SCL_CONFIG, FTAG, RW_READER);
5299 
5300 	for (i = 0; i < 4; i++) {
5301 		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
5302 		int t = (i & 1) ? type : ZDB_OT_TOTAL;
5303 		int equal;
5304 		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
5305 
5306 		zb->zb_asize += BP_GET_ASIZE(bp);
5307 		zb->zb_lsize += BP_GET_LSIZE(bp);
5308 		zb->zb_psize += BP_GET_PSIZE(bp);
5309 		zb->zb_count++;
5310 
5311 		/*
5312 		 * The histogram is only big enough to record blocks up to
5313 		 * SPA_OLD_MAXBLOCKSIZE; larger blocks go into the last,
5314 		 * "other", bucket.
5315 		 */
5316 		unsigned idx = BP_GET_PSIZE(bp) >> SPA_MINBLOCKSHIFT;
5317 		idx = MIN(idx, SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 1);
5318 		zb->zb_psize_histogram[idx]++;
5319 
5320 		zb->zb_gangs += BP_COUNT_GANG(bp);
5321 
5322 		switch (BP_GET_NDVAS(bp)) {
5323 		case 2:
5324 			if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5325 			    DVA_GET_VDEV(&bp->blk_dva[1])) {
5326 				zb->zb_ditto_samevdev++;
5327 
5328 				if (same_metaslab(zcb->zcb_spa,
5329 				    DVA_GET_VDEV(&bp->blk_dva[0]),
5330 				    DVA_GET_OFFSET(&bp->blk_dva[0]),
5331 				    DVA_GET_OFFSET(&bp->blk_dva[1])))
5332 					zb->zb_ditto_same_ms++;
5333 			}
5334 			break;
5335 		case 3:
5336 			equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5337 			    DVA_GET_VDEV(&bp->blk_dva[1])) +
5338 			    (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5339 			    DVA_GET_VDEV(&bp->blk_dva[2])) +
5340 			    (DVA_GET_VDEV(&bp->blk_dva[1]) ==
5341 			    DVA_GET_VDEV(&bp->blk_dva[2]));
5342 			if (equal != 0) {
5343 				zb->zb_ditto_samevdev++;
5344 
5345 				if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5346 				    DVA_GET_VDEV(&bp->blk_dva[1]) &&
5347 				    same_metaslab(zcb->zcb_spa,
5348 				    DVA_GET_VDEV(&bp->blk_dva[0]),
5349 				    DVA_GET_OFFSET(&bp->blk_dva[0]),
5350 				    DVA_GET_OFFSET(&bp->blk_dva[1])))
5351 					zb->zb_ditto_same_ms++;
5352 				else if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
5353 				    DVA_GET_VDEV(&bp->blk_dva[2]) &&
5354 				    same_metaslab(zcb->zcb_spa,
5355 				    DVA_GET_VDEV(&bp->blk_dva[0]),
5356 				    DVA_GET_OFFSET(&bp->blk_dva[0]),
5357 				    DVA_GET_OFFSET(&bp->blk_dva[2])))
5358 					zb->zb_ditto_same_ms++;
5359 				else if (DVA_GET_VDEV(&bp->blk_dva[1]) ==
5360 				    DVA_GET_VDEV(&bp->blk_dva[2]) &&
5361 				    same_metaslab(zcb->zcb_spa,
5362 				    DVA_GET_VDEV(&bp->blk_dva[1]),
5363 				    DVA_GET_OFFSET(&bp->blk_dva[1]),
5364 				    DVA_GET_OFFSET(&bp->blk_dva[2])))
5365 					zb->zb_ditto_same_ms++;
5366 			}
5367 			break;
5368 		}
5369 	}
5370 
5371 	spa_config_exit(zcb->zcb_spa, SCL_CONFIG, FTAG);
5372 
5373 	if (BP_IS_EMBEDDED(bp)) {
5374 		zcb->zcb_embedded_blocks[BPE_GET_ETYPE(bp)]++;
5375 		zcb->zcb_embedded_histogram[BPE_GET_ETYPE(bp)]
5376 		    [BPE_GET_PSIZE(bp)]++;
5377 		return;
5378 	}
5379 	/*
5380 	 * The binning histogram bins by powers of two up to
5381 	 * SPA_MAXBLOCKSIZE rather than creating bins for
5382 	 * every possible blocksize found in the pool.
5383 	 */
5384 	int bin = highbit64(BP_GET_PSIZE(bp)) - 1;
5385 
5386 	zcb->zcb_psize_count[bin]++;
5387 	zcb->zcb_psize_len[bin] += BP_GET_PSIZE(bp);
5388 	zcb->zcb_psize_total += BP_GET_PSIZE(bp);
5389 
5390 	bin = highbit64(BP_GET_LSIZE(bp)) - 1;
5391 
5392 	zcb->zcb_lsize_count[bin]++;
5393 	zcb->zcb_lsize_len[bin] += BP_GET_LSIZE(bp);
5394 	zcb->zcb_lsize_total += BP_GET_LSIZE(bp);
5395 
5396 	bin = highbit64(BP_GET_ASIZE(bp)) - 1;
5397 
5398 	zcb->zcb_asize_count[bin]++;
5399 	zcb->zcb_asize_len[bin] += BP_GET_ASIZE(bp);
5400 	zcb->zcb_asize_total += BP_GET_ASIZE(bp);
5401 
5402 	if (dump_opt['L'])
5403 		return;
5404 
5405 	if (BP_GET_DEDUP(bp)) {
5406 		ddt_t *ddt;
5407 		ddt_entry_t *dde;
5408 
5409 		ddt = ddt_select(zcb->zcb_spa, bp);
5410 		ddt_enter(ddt);
5411 		dde = ddt_lookup(ddt, bp, B_FALSE);
5412 
5413 		if (dde == NULL) {
5414 			refcnt = 0;
5415 		} else {
5416 			ddt_phys_t *ddp = ddt_phys_select(dde, bp);
5417 			ddt_phys_decref(ddp);
5418 			refcnt = ddp->ddp_refcnt;
5419 			if (ddt_phys_total_refcnt(dde) == 0)
5420 				ddt_remove(ddt, dde);
5421 		}
5422 		ddt_exit(ddt);
5423 	}
5424 
5425 	VERIFY3U(zio_wait(zio_claim(NULL, zcb->zcb_spa,
5426 	    refcnt ? 0 : spa_min_claim_txg(zcb->zcb_spa),
5427 	    bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
5428 }
5429 
5430 static void
5431 zdb_blkptr_done(zio_t *zio)
5432 {
5433 	spa_t *spa = zio->io_spa;
5434 	blkptr_t *bp = zio->io_bp;
5435 	int ioerr = zio->io_error;
5436 	zdb_cb_t *zcb = zio->io_private;
5437 	zbookmark_phys_t *zb = &zio->io_bookmark;
5438 
5439 	mutex_enter(&spa->spa_scrub_lock);
5440 	spa->spa_load_verify_bytes -= BP_GET_PSIZE(bp);
5441 	cv_broadcast(&spa->spa_scrub_io_cv);
5442 
5443 	if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
5444 		char blkbuf[BP_SPRINTF_LEN];
5445 
5446 		zcb->zcb_haderrors = 1;
5447 		zcb->zcb_errors[ioerr]++;
5448 
5449 		if (dump_opt['b'] >= 2)
5450 			snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
5451 		else
5452 			blkbuf[0] = '\0';
5453 
5454 		(void) printf("zdb_blkptr_cb: "
5455 		    "Got error %d reading "
5456 		    "<%llu, %llu, %lld, %llx> %s -- skipping\n",
5457 		    ioerr,
5458 		    (u_longlong_t)zb->zb_objset,
5459 		    (u_longlong_t)zb->zb_object,
5460 		    (u_longlong_t)zb->zb_level,
5461 		    (u_longlong_t)zb->zb_blkid,
5462 		    blkbuf);
5463 	}
5464 	mutex_exit(&spa->spa_scrub_lock);
5465 
5466 	abd_free(zio->io_abd);
5467 }
5468 
5469 static int
5470 zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
5471     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
5472 {
5473 	zdb_cb_t *zcb = arg;
5474 	dmu_object_type_t type;
5475 	boolean_t is_metadata;
5476 
5477 	if (zb->zb_level == ZB_DNODE_LEVEL)
5478 		return (0);
5479 
5480 	if (dump_opt['b'] >= 5 && bp->blk_birth > 0) {
5481 		char blkbuf[BP_SPRINTF_LEN];
5482 		snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
5483 		(void) printf("objset %llu object %llu "
5484 		    "level %lld offset 0x%llx %s\n",
5485 		    (u_longlong_t)zb->zb_objset,
5486 		    (u_longlong_t)zb->zb_object,
5487 		    (longlong_t)zb->zb_level,
5488 		    (u_longlong_t)blkid2offset(dnp, bp, zb),
5489 		    blkbuf);
5490 	}
5491 
5492 	if (BP_IS_HOLE(bp) || BP_IS_REDACTED(bp))
5493 		return (0);
5494 
5495 	type = BP_GET_TYPE(bp);
5496 
5497 	zdb_count_block(zcb, zilog, bp,
5498 	    (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
5499 
5500 	is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
5501 
5502 	if (!BP_IS_EMBEDDED(bp) &&
5503 	    (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata))) {
5504 		size_t size = BP_GET_PSIZE(bp);
5505 		abd_t *abd = abd_alloc(size, B_FALSE);
5506 		int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
5507 
5508 		/* If it's an intent log block, failure is expected. */
5509 		if (zb->zb_level == ZB_ZIL_LEVEL)
5510 			flags |= ZIO_FLAG_SPECULATIVE;
5511 
5512 		mutex_enter(&spa->spa_scrub_lock);
5513 		while (spa->spa_load_verify_bytes > max_inflight_bytes)
5514 			cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
5515 		spa->spa_load_verify_bytes += size;
5516 		mutex_exit(&spa->spa_scrub_lock);
5517 
5518 		zio_nowait(zio_read(NULL, spa, bp, abd, size,
5519 		    zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
5520 	}
5521 
5522 	zcb->zcb_readfails = 0;
5523 
5524 	/* only call gethrtime() every 100 blocks */
5525 	static int iters;
5526 	if (++iters > 100)
5527 		iters = 0;
5528 	else
5529 		return (0);
5530 
5531 	if (dump_opt['b'] < 5 && gethrtime() > zcb->zcb_lastprint + NANOSEC) {
5532 		uint64_t now = gethrtime();
5533 		char buf[10];
5534 		uint64_t bytes = zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL].zb_asize;
5535 		uint64_t kb_per_sec =
5536 		    1 + bytes / (1 + ((now - zcb->zcb_start) / 1000 / 1000));
5537 		uint64_t sec_remaining =
5538 		    (zcb->zcb_totalasize - bytes) / 1024 / kb_per_sec;
5539 
5540 		/* make sure nicenum has enough space */
5541 		_Static_assert(sizeof (buf) >= NN_NUMBUF_SZ, "buf truncated");
5542 
5543 		zfs_nicebytes(bytes, buf, sizeof (buf));
5544 		(void) fprintf(stderr,
5545 		    "\r%5s completed (%4"PRIu64"MB/s) "
5546 		    "estimated time remaining: "
5547 		    "%"PRIu64"hr %02"PRIu64"min %02"PRIu64"sec        ",
5548 		    buf, kb_per_sec / 1024,
5549 		    sec_remaining / 60 / 60,
5550 		    sec_remaining / 60 % 60,
5551 		    sec_remaining % 60);
5552 
5553 		zcb->zcb_lastprint = now;
5554 	}
5555 
5556 	return (0);
5557 }
5558 
5559 static void
5560 zdb_leak(void *arg, uint64_t start, uint64_t size)
5561 {
5562 	vdev_t *vd = arg;
5563 
5564 	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
5565 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
5566 }
5567 
5568 static metaslab_ops_t zdb_metaslab_ops = {
5569 	NULL	/* alloc */
5570 };
5571 
5572 static int
5573 load_unflushed_svr_segs_cb(spa_t *spa, space_map_entry_t *sme,
5574     uint64_t txg, void *arg)
5575 {
5576 	spa_vdev_removal_t *svr = arg;
5577 
5578 	uint64_t offset = sme->sme_offset;
5579 	uint64_t size = sme->sme_run;
5580 
5581 	/* skip vdevs we don't care about */
5582 	if (sme->sme_vdev != svr->svr_vdev_id)
5583 		return (0);
5584 
5585 	vdev_t *vd = vdev_lookup_top(spa, sme->sme_vdev);
5586 	metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5587 	ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
5588 
5589 	if (txg < metaslab_unflushed_txg(ms))
5590 		return (0);
5591 
5592 	if (sme->sme_type == SM_ALLOC)
5593 		range_tree_add(svr->svr_allocd_segs, offset, size);
5594 	else
5595 		range_tree_remove(svr->svr_allocd_segs, offset, size);
5596 
5597 	return (0);
5598 }
5599 
5600 static void
5601 claim_segment_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5602     uint64_t size, void *arg)
5603 {
5604 	(void) inner_offset, (void) arg;
5605 
5606 	/*
5607 	 * This callback was called through a remap from
5608 	 * a device being removed. Therefore, the vdev that
5609 	 * this callback is applied to is a concrete
5610 	 * vdev.
5611 	 */
5612 	ASSERT(vdev_is_concrete(vd));
5613 
5614 	VERIFY0(metaslab_claim_impl(vd, offset, size,
5615 	    spa_min_claim_txg(vd->vdev_spa)));
5616 }
5617 
5618 static void
5619 claim_segment_cb(void *arg, uint64_t offset, uint64_t size)
5620 {
5621 	vdev_t *vd = arg;
5622 
5623 	vdev_indirect_ops.vdev_op_remap(vd, offset, size,
5624 	    claim_segment_impl_cb, NULL);
5625 }
5626 
5627 /*
5628  * After accounting for all allocated blocks that are directly referenced,
5629  * we might have missed a reference to a block from a partially complete
5630  * (and thus unused) indirect mapping object. We perform a secondary pass
5631  * through the metaslabs we have already mapped and claim the destination
5632  * blocks.
5633  */
5634 static void
5635 zdb_claim_removing(spa_t *spa, zdb_cb_t *zcb)
5636 {
5637 	if (dump_opt['L'])
5638 		return;
5639 
5640 	if (spa->spa_vdev_removal == NULL)
5641 		return;
5642 
5643 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5644 
5645 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
5646 	vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
5647 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
5648 
5649 	ASSERT0(range_tree_space(svr->svr_allocd_segs));
5650 
5651 	range_tree_t *allocs = range_tree_create(NULL, RANGE_SEG64, NULL, 0, 0);
5652 	for (uint64_t msi = 0; msi < vd->vdev_ms_count; msi++) {
5653 		metaslab_t *msp = vd->vdev_ms[msi];
5654 
5655 		ASSERT0(range_tree_space(allocs));
5656 		if (msp->ms_sm != NULL)
5657 			VERIFY0(space_map_load(msp->ms_sm, allocs, SM_ALLOC));
5658 		range_tree_vacate(allocs, range_tree_add, svr->svr_allocd_segs);
5659 	}
5660 	range_tree_destroy(allocs);
5661 
5662 	iterate_through_spacemap_logs(spa, load_unflushed_svr_segs_cb, svr);
5663 
5664 	/*
5665 	 * Clear everything past what has been synced,
5666 	 * because we have not allocated mappings for
5667 	 * it yet.
5668 	 */
5669 	range_tree_clear(svr->svr_allocd_segs,
5670 	    vdev_indirect_mapping_max_offset(vim),
5671 	    vd->vdev_asize - vdev_indirect_mapping_max_offset(vim));
5672 
5673 	zcb->zcb_removing_size += range_tree_space(svr->svr_allocd_segs);
5674 	range_tree_vacate(svr->svr_allocd_segs, claim_segment_cb, vd);
5675 
5676 	spa_config_exit(spa, SCL_CONFIG, FTAG);
5677 }
5678 
5679 static int
5680 increment_indirect_mapping_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
5681     dmu_tx_t *tx)
5682 {
5683 	(void) tx;
5684 	zdb_cb_t *zcb = arg;
5685 	spa_t *spa = zcb->zcb_spa;
5686 	vdev_t *vd;
5687 	const dva_t *dva = &bp->blk_dva[0];
5688 
5689 	ASSERT(!bp_freed);
5690 	ASSERT(!dump_opt['L']);
5691 	ASSERT3U(BP_GET_NDVAS(bp), ==, 1);
5692 
5693 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
5694 	vd = vdev_lookup_top(zcb->zcb_spa, DVA_GET_VDEV(dva));
5695 	ASSERT3P(vd, !=, NULL);
5696 	spa_config_exit(spa, SCL_VDEV, FTAG);
5697 
5698 	ASSERT(vd->vdev_indirect_config.vic_mapping_object != 0);
5699 	ASSERT3P(zcb->zcb_vd_obsolete_counts[vd->vdev_id], !=, NULL);
5700 
5701 	vdev_indirect_mapping_increment_obsolete_count(
5702 	    vd->vdev_indirect_mapping,
5703 	    DVA_GET_OFFSET(dva), DVA_GET_ASIZE(dva),
5704 	    zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
5705 
5706 	return (0);
5707 }
5708 
5709 static uint32_t *
5710 zdb_load_obsolete_counts(vdev_t *vd)
5711 {
5712 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
5713 	spa_t *spa = vd->vdev_spa;
5714 	spa_condensing_indirect_phys_t *scip =
5715 	    &spa->spa_condensing_indirect_phys;
5716 	uint64_t obsolete_sm_object;
5717 	uint32_t *counts;
5718 
5719 	VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
5720 	EQUIV(obsolete_sm_object != 0, vd->vdev_obsolete_sm != NULL);
5721 	counts = vdev_indirect_mapping_load_obsolete_counts(vim);
5722 	if (vd->vdev_obsolete_sm != NULL) {
5723 		vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
5724 		    vd->vdev_obsolete_sm);
5725 	}
5726 	if (scip->scip_vdev == vd->vdev_id &&
5727 	    scip->scip_prev_obsolete_sm_object != 0) {
5728 		space_map_t *prev_obsolete_sm = NULL;
5729 		VERIFY0(space_map_open(&prev_obsolete_sm, spa->spa_meta_objset,
5730 		    scip->scip_prev_obsolete_sm_object, 0, vd->vdev_asize, 0));
5731 		vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
5732 		    prev_obsolete_sm);
5733 		space_map_close(prev_obsolete_sm);
5734 	}
5735 	return (counts);
5736 }
5737 
5738 static void
5739 zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
5740 {
5741 	ddt_bookmark_t ddb = {0};
5742 	ddt_entry_t dde;
5743 	int error;
5744 	int p;
5745 
5746 	ASSERT(!dump_opt['L']);
5747 
5748 	while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
5749 		blkptr_t blk;
5750 		ddt_phys_t *ddp = dde.dde_phys;
5751 
5752 		if (ddb.ddb_class == DDT_CLASS_UNIQUE)
5753 			return;
5754 
5755 		ASSERT(ddt_phys_total_refcnt(&dde) > 1);
5756 
5757 		for (p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
5758 			if (ddp->ddp_phys_birth == 0)
5759 				continue;
5760 			ddt_bp_create(ddb.ddb_checksum,
5761 			    &dde.dde_key, ddp, &blk);
5762 			if (p == DDT_PHYS_DITTO) {
5763 				zdb_count_block(zcb, NULL, &blk, ZDB_OT_DITTO);
5764 			} else {
5765 				zcb->zcb_dedup_asize +=
5766 				    BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
5767 				zcb->zcb_dedup_blocks++;
5768 			}
5769 		}
5770 		ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
5771 		ddt_enter(ddt);
5772 		VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
5773 		ddt_exit(ddt);
5774 	}
5775 
5776 	ASSERT(error == ENOENT);
5777 }
5778 
5779 typedef struct checkpoint_sm_exclude_entry_arg {
5780 	vdev_t *cseea_vd;
5781 	uint64_t cseea_checkpoint_size;
5782 } checkpoint_sm_exclude_entry_arg_t;
5783 
5784 static int
5785 checkpoint_sm_exclude_entry_cb(space_map_entry_t *sme, void *arg)
5786 {
5787 	checkpoint_sm_exclude_entry_arg_t *cseea = arg;
5788 	vdev_t *vd = cseea->cseea_vd;
5789 	metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
5790 	uint64_t end = sme->sme_offset + sme->sme_run;
5791 
5792 	ASSERT(sme->sme_type == SM_FREE);
5793 
5794 	/*
5795 	 * Since the vdev_checkpoint_sm exists in the vdev level
5796 	 * and the ms_sm space maps exist in the metaslab level,
5797 	 * an entry in the checkpoint space map could theoretically
5798 	 * cross the boundaries of the metaslab that it belongs.
5799 	 *
5800 	 * In reality, because of the way that we populate and
5801 	 * manipulate the checkpoint's space maps currently,
5802 	 * there shouldn't be any entries that cross metaslabs.
5803 	 * Hence the assertion below.
5804 	 *
5805 	 * That said, there is no fundamental requirement that
5806 	 * the checkpoint's space map entries should not cross
5807 	 * metaslab boundaries. So if needed we could add code
5808 	 * that handles metaslab-crossing segments in the future.
5809 	 */
5810 	VERIFY3U(sme->sme_offset, >=, ms->ms_start);
5811 	VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
5812 
5813 	/*
5814 	 * By removing the entry from the allocated segments we
5815 	 * also verify that the entry is there to begin with.
5816 	 */
5817 	mutex_enter(&ms->ms_lock);
5818 	range_tree_remove(ms->ms_allocatable, sme->sme_offset, sme->sme_run);
5819 	mutex_exit(&ms->ms_lock);
5820 
5821 	cseea->cseea_checkpoint_size += sme->sme_run;
5822 	return (0);
5823 }
5824 
5825 static void
5826 zdb_leak_init_vdev_exclude_checkpoint(vdev_t *vd, zdb_cb_t *zcb)
5827 {
5828 	spa_t *spa = vd->vdev_spa;
5829 	space_map_t *checkpoint_sm = NULL;
5830 	uint64_t checkpoint_sm_obj;
5831 
5832 	/*
5833 	 * If there is no vdev_top_zap, we are in a pool whose
5834 	 * version predates the pool checkpoint feature.
5835 	 */
5836 	if (vd->vdev_top_zap == 0)
5837 		return;
5838 
5839 	/*
5840 	 * If there is no reference of the vdev_checkpoint_sm in
5841 	 * the vdev_top_zap, then one of the following scenarios
5842 	 * is true:
5843 	 *
5844 	 * 1] There is no checkpoint
5845 	 * 2] There is a checkpoint, but no checkpointed blocks
5846 	 *    have been freed yet
5847 	 * 3] The current vdev is indirect
5848 	 *
5849 	 * In these cases we return immediately.
5850 	 */
5851 	if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
5852 	    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
5853 		return;
5854 
5855 	VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
5856 	    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1,
5857 	    &checkpoint_sm_obj));
5858 
5859 	checkpoint_sm_exclude_entry_arg_t cseea;
5860 	cseea.cseea_vd = vd;
5861 	cseea.cseea_checkpoint_size = 0;
5862 
5863 	VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
5864 	    checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
5865 
5866 	VERIFY0(space_map_iterate(checkpoint_sm,
5867 	    space_map_length(checkpoint_sm),
5868 	    checkpoint_sm_exclude_entry_cb, &cseea));
5869 	space_map_close(checkpoint_sm);
5870 
5871 	zcb->zcb_checkpoint_size += cseea.cseea_checkpoint_size;
5872 }
5873 
5874 static void
5875 zdb_leak_init_exclude_checkpoint(spa_t *spa, zdb_cb_t *zcb)
5876 {
5877 	ASSERT(!dump_opt['L']);
5878 
5879 	vdev_t *rvd = spa->spa_root_vdev;
5880 	for (uint64_t c = 0; c < rvd->vdev_children; c++) {
5881 		ASSERT3U(c, ==, rvd->vdev_child[c]->vdev_id);
5882 		zdb_leak_init_vdev_exclude_checkpoint(rvd->vdev_child[c], zcb);
5883 	}
5884 }
5885 
5886 static int
5887 count_unflushed_space_cb(spa_t *spa, space_map_entry_t *sme,
5888     uint64_t txg, void *arg)
5889 {
5890 	int64_t *ualloc_space = arg;
5891 
5892 	uint64_t offset = sme->sme_offset;
5893 	uint64_t vdev_id = sme->sme_vdev;
5894 
5895 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
5896 	if (!vdev_is_concrete(vd))
5897 		return (0);
5898 
5899 	metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5900 	ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
5901 
5902 	if (txg < metaslab_unflushed_txg(ms))
5903 		return (0);
5904 
5905 	if (sme->sme_type == SM_ALLOC)
5906 		*ualloc_space += sme->sme_run;
5907 	else
5908 		*ualloc_space -= sme->sme_run;
5909 
5910 	return (0);
5911 }
5912 
5913 static int64_t
5914 get_unflushed_alloc_space(spa_t *spa)
5915 {
5916 	if (dump_opt['L'])
5917 		return (0);
5918 
5919 	int64_t ualloc_space = 0;
5920 	iterate_through_spacemap_logs(spa, count_unflushed_space_cb,
5921 	    &ualloc_space);
5922 	return (ualloc_space);
5923 }
5924 
5925 static int
5926 load_unflushed_cb(spa_t *spa, space_map_entry_t *sme, uint64_t txg, void *arg)
5927 {
5928 	maptype_t *uic_maptype = arg;
5929 
5930 	uint64_t offset = sme->sme_offset;
5931 	uint64_t size = sme->sme_run;
5932 	uint64_t vdev_id = sme->sme_vdev;
5933 
5934 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
5935 
5936 	/* skip indirect vdevs */
5937 	if (!vdev_is_concrete(vd))
5938 		return (0);
5939 
5940 	metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5941 
5942 	ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
5943 	ASSERT(*uic_maptype == SM_ALLOC || *uic_maptype == SM_FREE);
5944 
5945 	if (txg < metaslab_unflushed_txg(ms))
5946 		return (0);
5947 
5948 	if (*uic_maptype == sme->sme_type)
5949 		range_tree_add(ms->ms_allocatable, offset, size);
5950 	else
5951 		range_tree_remove(ms->ms_allocatable, offset, size);
5952 
5953 	return (0);
5954 }
5955 
5956 static void
5957 load_unflushed_to_ms_allocatables(spa_t *spa, maptype_t maptype)
5958 {
5959 	iterate_through_spacemap_logs(spa, load_unflushed_cb, &maptype);
5960 }
5961 
5962 static void
5963 load_concrete_ms_allocatable_trees(spa_t *spa, maptype_t maptype)
5964 {
5965 	vdev_t *rvd = spa->spa_root_vdev;
5966 	for (uint64_t i = 0; i < rvd->vdev_children; i++) {
5967 		vdev_t *vd = rvd->vdev_child[i];
5968 
5969 		ASSERT3U(i, ==, vd->vdev_id);
5970 
5971 		if (vd->vdev_ops == &vdev_indirect_ops)
5972 			continue;
5973 
5974 		for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
5975 			metaslab_t *msp = vd->vdev_ms[m];
5976 
5977 			(void) fprintf(stderr,
5978 			    "\rloading concrete vdev %llu, "
5979 			    "metaslab %llu of %llu ...",
5980 			    (longlong_t)vd->vdev_id,
5981 			    (longlong_t)msp->ms_id,
5982 			    (longlong_t)vd->vdev_ms_count);
5983 
5984 			mutex_enter(&msp->ms_lock);
5985 			range_tree_vacate(msp->ms_allocatable, NULL, NULL);
5986 
5987 			/*
5988 			 * We don't want to spend the CPU manipulating the
5989 			 * size-ordered tree, so clear the range_tree ops.
5990 			 */
5991 			msp->ms_allocatable->rt_ops = NULL;
5992 
5993 			if (msp->ms_sm != NULL) {
5994 				VERIFY0(space_map_load(msp->ms_sm,
5995 				    msp->ms_allocatable, maptype));
5996 			}
5997 			if (!msp->ms_loaded)
5998 				msp->ms_loaded = B_TRUE;
5999 			mutex_exit(&msp->ms_lock);
6000 		}
6001 	}
6002 
6003 	load_unflushed_to_ms_allocatables(spa, maptype);
6004 }
6005 
6006 /*
6007  * vm_idxp is an in-out parameter which (for indirect vdevs) is the
6008  * index in vim_entries that has the first entry in this metaslab.
6009  * On return, it will be set to the first entry after this metaslab.
6010  */
6011 static void
6012 load_indirect_ms_allocatable_tree(vdev_t *vd, metaslab_t *msp,
6013     uint64_t *vim_idxp)
6014 {
6015 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6016 
6017 	mutex_enter(&msp->ms_lock);
6018 	range_tree_vacate(msp->ms_allocatable, NULL, NULL);
6019 
6020 	/*
6021 	 * We don't want to spend the CPU manipulating the
6022 	 * size-ordered tree, so clear the range_tree ops.
6023 	 */
6024 	msp->ms_allocatable->rt_ops = NULL;
6025 
6026 	for (; *vim_idxp < vdev_indirect_mapping_num_entries(vim);
6027 	    (*vim_idxp)++) {
6028 		vdev_indirect_mapping_entry_phys_t *vimep =
6029 		    &vim->vim_entries[*vim_idxp];
6030 		uint64_t ent_offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
6031 		uint64_t ent_len = DVA_GET_ASIZE(&vimep->vimep_dst);
6032 		ASSERT3U(ent_offset, >=, msp->ms_start);
6033 		if (ent_offset >= msp->ms_start + msp->ms_size)
6034 			break;
6035 
6036 		/*
6037 		 * Mappings do not cross metaslab boundaries,
6038 		 * because we create them by walking the metaslabs.
6039 		 */
6040 		ASSERT3U(ent_offset + ent_len, <=,
6041 		    msp->ms_start + msp->ms_size);
6042 		range_tree_add(msp->ms_allocatable, ent_offset, ent_len);
6043 	}
6044 
6045 	if (!msp->ms_loaded)
6046 		msp->ms_loaded = B_TRUE;
6047 	mutex_exit(&msp->ms_lock);
6048 }
6049 
6050 static void
6051 zdb_leak_init_prepare_indirect_vdevs(spa_t *spa, zdb_cb_t *zcb)
6052 {
6053 	ASSERT(!dump_opt['L']);
6054 
6055 	vdev_t *rvd = spa->spa_root_vdev;
6056 	for (uint64_t c = 0; c < rvd->vdev_children; c++) {
6057 		vdev_t *vd = rvd->vdev_child[c];
6058 
6059 		ASSERT3U(c, ==, vd->vdev_id);
6060 
6061 		if (vd->vdev_ops != &vdev_indirect_ops)
6062 			continue;
6063 
6064 		/*
6065 		 * Note: we don't check for mapping leaks on
6066 		 * removing vdevs because their ms_allocatable's
6067 		 * are used to look for leaks in allocated space.
6068 		 */
6069 		zcb->zcb_vd_obsolete_counts[c] = zdb_load_obsolete_counts(vd);
6070 
6071 		/*
6072 		 * Normally, indirect vdevs don't have any
6073 		 * metaslabs.  We want to set them up for
6074 		 * zio_claim().
6075 		 */
6076 		vdev_metaslab_group_create(vd);
6077 		VERIFY0(vdev_metaslab_init(vd, 0));
6078 
6079 		vdev_indirect_mapping_t *vim __maybe_unused =
6080 		    vd->vdev_indirect_mapping;
6081 		uint64_t vim_idx = 0;
6082 		for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
6083 
6084 			(void) fprintf(stderr,
6085 			    "\rloading indirect vdev %llu, "
6086 			    "metaslab %llu of %llu ...",
6087 			    (longlong_t)vd->vdev_id,
6088 			    (longlong_t)vd->vdev_ms[m]->ms_id,
6089 			    (longlong_t)vd->vdev_ms_count);
6090 
6091 			load_indirect_ms_allocatable_tree(vd, vd->vdev_ms[m],
6092 			    &vim_idx);
6093 		}
6094 		ASSERT3U(vim_idx, ==, vdev_indirect_mapping_num_entries(vim));
6095 	}
6096 }
6097 
6098 static void
6099 zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
6100 {
6101 	zcb->zcb_spa = spa;
6102 
6103 	if (dump_opt['L'])
6104 		return;
6105 
6106 	dsl_pool_t *dp = spa->spa_dsl_pool;
6107 	vdev_t *rvd = spa->spa_root_vdev;
6108 
6109 	/*
6110 	 * We are going to be changing the meaning of the metaslab's
6111 	 * ms_allocatable.  Ensure that the allocator doesn't try to
6112 	 * use the tree.
6113 	 */
6114 	spa->spa_normal_class->mc_ops = &zdb_metaslab_ops;
6115 	spa->spa_log_class->mc_ops = &zdb_metaslab_ops;
6116 	spa->spa_embedded_log_class->mc_ops = &zdb_metaslab_ops;
6117 
6118 	zcb->zcb_vd_obsolete_counts =
6119 	    umem_zalloc(rvd->vdev_children * sizeof (uint32_t *),
6120 	    UMEM_NOFAIL);
6121 
6122 	/*
6123 	 * For leak detection, we overload the ms_allocatable trees
6124 	 * to contain allocated segments instead of free segments.
6125 	 * As a result, we can't use the normal metaslab_load/unload
6126 	 * interfaces.
6127 	 */
6128 	zdb_leak_init_prepare_indirect_vdevs(spa, zcb);
6129 	load_concrete_ms_allocatable_trees(spa, SM_ALLOC);
6130 
6131 	/*
6132 	 * On load_concrete_ms_allocatable_trees() we loaded all the
6133 	 * allocated entries from the ms_sm to the ms_allocatable for
6134 	 * each metaslab. If the pool has a checkpoint or is in the
6135 	 * middle of discarding a checkpoint, some of these blocks
6136 	 * may have been freed but their ms_sm may not have been
6137 	 * updated because they are referenced by the checkpoint. In
6138 	 * order to avoid false-positives during leak-detection, we
6139 	 * go through the vdev's checkpoint space map and exclude all
6140 	 * its entries from their relevant ms_allocatable.
6141 	 *
6142 	 * We also aggregate the space held by the checkpoint and add
6143 	 * it to zcb_checkpoint_size.
6144 	 *
6145 	 * Note that at this point we are also verifying that all the
6146 	 * entries on the checkpoint_sm are marked as allocated in
6147 	 * the ms_sm of their relevant metaslab.
6148 	 * [see comment in checkpoint_sm_exclude_entry_cb()]
6149 	 */
6150 	zdb_leak_init_exclude_checkpoint(spa, zcb);
6151 	ASSERT3U(zcb->zcb_checkpoint_size, ==, spa_get_checkpoint_space(spa));
6152 
6153 	/* for cleaner progress output */
6154 	(void) fprintf(stderr, "\n");
6155 
6156 	if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
6157 		ASSERT(spa_feature_is_enabled(spa,
6158 		    SPA_FEATURE_DEVICE_REMOVAL));
6159 		(void) bpobj_iterate_nofree(&dp->dp_obsolete_bpobj,
6160 		    increment_indirect_mapping_cb, zcb, NULL);
6161 	}
6162 
6163 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6164 	zdb_ddt_leak_init(spa, zcb);
6165 	spa_config_exit(spa, SCL_CONFIG, FTAG);
6166 }
6167 
6168 static boolean_t
6169 zdb_check_for_obsolete_leaks(vdev_t *vd, zdb_cb_t *zcb)
6170 {
6171 	boolean_t leaks = B_FALSE;
6172 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6173 	uint64_t total_leaked = 0;
6174 	boolean_t are_precise = B_FALSE;
6175 
6176 	ASSERT(vim != NULL);
6177 
6178 	for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
6179 		vdev_indirect_mapping_entry_phys_t *vimep =
6180 		    &vim->vim_entries[i];
6181 		uint64_t obsolete_bytes = 0;
6182 		uint64_t offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
6183 		metaslab_t *msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
6184 
6185 		/*
6186 		 * This is not very efficient but it's easy to
6187 		 * verify correctness.
6188 		 */
6189 		for (uint64_t inner_offset = 0;
6190 		    inner_offset < DVA_GET_ASIZE(&vimep->vimep_dst);
6191 		    inner_offset += 1 << vd->vdev_ashift) {
6192 			if (range_tree_contains(msp->ms_allocatable,
6193 			    offset + inner_offset, 1 << vd->vdev_ashift)) {
6194 				obsolete_bytes += 1 << vd->vdev_ashift;
6195 			}
6196 		}
6197 
6198 		int64_t bytes_leaked = obsolete_bytes -
6199 		    zcb->zcb_vd_obsolete_counts[vd->vdev_id][i];
6200 		ASSERT3U(DVA_GET_ASIZE(&vimep->vimep_dst), >=,
6201 		    zcb->zcb_vd_obsolete_counts[vd->vdev_id][i]);
6202 
6203 		VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
6204 		if (bytes_leaked != 0 && (are_precise || dump_opt['d'] >= 5)) {
6205 			(void) printf("obsolete indirect mapping count "
6206 			    "mismatch on %llu:%llx:%llx : %llx bytes leaked\n",
6207 			    (u_longlong_t)vd->vdev_id,
6208 			    (u_longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
6209 			    (u_longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
6210 			    (u_longlong_t)bytes_leaked);
6211 		}
6212 		total_leaked += ABS(bytes_leaked);
6213 	}
6214 
6215 	VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
6216 	if (!are_precise && total_leaked > 0) {
6217 		int pct_leaked = total_leaked * 100 /
6218 		    vdev_indirect_mapping_bytes_mapped(vim);
6219 		(void) printf("cannot verify obsolete indirect mapping "
6220 		    "counts of vdev %llu because precise feature was not "
6221 		    "enabled when it was removed: %d%% (%llx bytes) of mapping"
6222 		    "unreferenced\n",
6223 		    (u_longlong_t)vd->vdev_id, pct_leaked,
6224 		    (u_longlong_t)total_leaked);
6225 	} else if (total_leaked > 0) {
6226 		(void) printf("obsolete indirect mapping count mismatch "
6227 		    "for vdev %llu -- %llx total bytes mismatched\n",
6228 		    (u_longlong_t)vd->vdev_id,
6229 		    (u_longlong_t)total_leaked);
6230 		leaks |= B_TRUE;
6231 	}
6232 
6233 	vdev_indirect_mapping_free_obsolete_counts(vim,
6234 	    zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
6235 	zcb->zcb_vd_obsolete_counts[vd->vdev_id] = NULL;
6236 
6237 	return (leaks);
6238 }
6239 
6240 static boolean_t
6241 zdb_leak_fini(spa_t *spa, zdb_cb_t *zcb)
6242 {
6243 	if (dump_opt['L'])
6244 		return (B_FALSE);
6245 
6246 	boolean_t leaks = B_FALSE;
6247 	vdev_t *rvd = spa->spa_root_vdev;
6248 	for (unsigned c = 0; c < rvd->vdev_children; c++) {
6249 		vdev_t *vd = rvd->vdev_child[c];
6250 
6251 		if (zcb->zcb_vd_obsolete_counts[c] != NULL) {
6252 			leaks |= zdb_check_for_obsolete_leaks(vd, zcb);
6253 		}
6254 
6255 		for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
6256 			metaslab_t *msp = vd->vdev_ms[m];
6257 			ASSERT3P(msp->ms_group, ==, (msp->ms_group->mg_class ==
6258 			    spa_embedded_log_class(spa)) ?
6259 			    vd->vdev_log_mg : vd->vdev_mg);
6260 
6261 			/*
6262 			 * ms_allocatable has been overloaded
6263 			 * to contain allocated segments. Now that
6264 			 * we finished traversing all blocks, any
6265 			 * block that remains in the ms_allocatable
6266 			 * represents an allocated block that we
6267 			 * did not claim during the traversal.
6268 			 * Claimed blocks would have been removed
6269 			 * from the ms_allocatable.  For indirect
6270 			 * vdevs, space remaining in the tree
6271 			 * represents parts of the mapping that are
6272 			 * not referenced, which is not a bug.
6273 			 */
6274 			if (vd->vdev_ops == &vdev_indirect_ops) {
6275 				range_tree_vacate(msp->ms_allocatable,
6276 				    NULL, NULL);
6277 			} else {
6278 				range_tree_vacate(msp->ms_allocatable,
6279 				    zdb_leak, vd);
6280 			}
6281 			if (msp->ms_loaded) {
6282 				msp->ms_loaded = B_FALSE;
6283 			}
6284 		}
6285 	}
6286 
6287 	umem_free(zcb->zcb_vd_obsolete_counts,
6288 	    rvd->vdev_children * sizeof (uint32_t *));
6289 	zcb->zcb_vd_obsolete_counts = NULL;
6290 
6291 	return (leaks);
6292 }
6293 
6294 static int
6295 count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
6296 {
6297 	(void) tx;
6298 	zdb_cb_t *zcb = arg;
6299 
6300 	if (dump_opt['b'] >= 5) {
6301 		char blkbuf[BP_SPRINTF_LEN];
6302 		snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
6303 		(void) printf("[%s] %s\n",
6304 		    "deferred free", blkbuf);
6305 	}
6306 	zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
6307 	return (0);
6308 }
6309 
6310 /*
6311  * Iterate over livelists which have been destroyed by the user but
6312  * are still present in the MOS, waiting to be freed
6313  */
6314 static void
6315 iterate_deleted_livelists(spa_t *spa, ll_iter_t func, void *arg)
6316 {
6317 	objset_t *mos = spa->spa_meta_objset;
6318 	uint64_t zap_obj;
6319 	int err = zap_lookup(mos, DMU_POOL_DIRECTORY_OBJECT,
6320 	    DMU_POOL_DELETED_CLONES, sizeof (uint64_t), 1, &zap_obj);
6321 	if (err == ENOENT)
6322 		return;
6323 	ASSERT0(err);
6324 
6325 	zap_cursor_t zc;
6326 	zap_attribute_t attr;
6327 	dsl_deadlist_t ll;
6328 	/* NULL out os prior to dsl_deadlist_open in case it's garbage */
6329 	ll.dl_os = NULL;
6330 	for (zap_cursor_init(&zc, mos, zap_obj);
6331 	    zap_cursor_retrieve(&zc, &attr) == 0;
6332 	    (void) zap_cursor_advance(&zc)) {
6333 		dsl_deadlist_open(&ll, mos, attr.za_first_integer);
6334 		func(&ll, arg);
6335 		dsl_deadlist_close(&ll);
6336 	}
6337 	zap_cursor_fini(&zc);
6338 }
6339 
6340 static int
6341 bpobj_count_block_cb(void *arg, const blkptr_t *bp, boolean_t bp_freed,
6342     dmu_tx_t *tx)
6343 {
6344 	ASSERT(!bp_freed);
6345 	return (count_block_cb(arg, bp, tx));
6346 }
6347 
6348 static int
6349 livelist_entry_count_blocks_cb(void *args, dsl_deadlist_entry_t *dle)
6350 {
6351 	zdb_cb_t *zbc = args;
6352 	bplist_t blks;
6353 	bplist_create(&blks);
6354 	/* determine which blocks have been alloc'd but not freed */
6355 	VERIFY0(dsl_process_sub_livelist(&dle->dle_bpobj, &blks, NULL, NULL));
6356 	/* count those blocks */
6357 	(void) bplist_iterate(&blks, count_block_cb, zbc, NULL);
6358 	bplist_destroy(&blks);
6359 	return (0);
6360 }
6361 
6362 static void
6363 livelist_count_blocks(dsl_deadlist_t *ll, void *arg)
6364 {
6365 	dsl_deadlist_iterate(ll, livelist_entry_count_blocks_cb, arg);
6366 }
6367 
6368 /*
6369  * Count the blocks in the livelists that have been destroyed by the user
6370  * but haven't yet been freed.
6371  */
6372 static void
6373 deleted_livelists_count_blocks(spa_t *spa, zdb_cb_t *zbc)
6374 {
6375 	iterate_deleted_livelists(spa, livelist_count_blocks, zbc);
6376 }
6377 
6378 static void
6379 dump_livelist_cb(dsl_deadlist_t *ll, void *arg)
6380 {
6381 	ASSERT3P(arg, ==, NULL);
6382 	global_feature_count[SPA_FEATURE_LIVELIST]++;
6383 	dump_blkptr_list(ll, "Deleted Livelist");
6384 	dsl_deadlist_iterate(ll, sublivelist_verify_lightweight, NULL);
6385 }
6386 
6387 /*
6388  * Print out, register object references to, and increment feature counts for
6389  * livelists that have been destroyed by the user but haven't yet been freed.
6390  */
6391 static void
6392 deleted_livelists_dump_mos(spa_t *spa)
6393 {
6394 	uint64_t zap_obj;
6395 	objset_t *mos = spa->spa_meta_objset;
6396 	int err = zap_lookup(mos, DMU_POOL_DIRECTORY_OBJECT,
6397 	    DMU_POOL_DELETED_CLONES, sizeof (uint64_t), 1, &zap_obj);
6398 	if (err == ENOENT)
6399 		return;
6400 	mos_obj_refd(zap_obj);
6401 	iterate_deleted_livelists(spa, dump_livelist_cb, NULL);
6402 }
6403 
6404 static int
6405 dump_block_stats(spa_t *spa)
6406 {
6407 	zdb_cb_t zcb = {{{{0}}}};
6408 	zdb_blkstats_t *zb, *tzb;
6409 	uint64_t norm_alloc, norm_space, total_alloc, total_found;
6410 	int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
6411 	    TRAVERSE_NO_DECRYPT | TRAVERSE_HARD;
6412 	boolean_t leaks = B_FALSE;
6413 	int e, c, err;
6414 	bp_embedded_type_t i;
6415 
6416 	(void) printf("\nTraversing all blocks %s%s%s%s%s...\n\n",
6417 	    (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
6418 	    (dump_opt['c'] == 1) ? "metadata " : "",
6419 	    dump_opt['c'] ? "checksums " : "",
6420 	    (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
6421 	    !dump_opt['L'] ? "nothing leaked " : "");
6422 
6423 	/*
6424 	 * When leak detection is enabled we load all space maps as SM_ALLOC
6425 	 * maps, then traverse the pool claiming each block we discover. If
6426 	 * the pool is perfectly consistent, the segment trees will be empty
6427 	 * when we're done. Anything left over is a leak; any block we can't
6428 	 * claim (because it's not part of any space map) is a double
6429 	 * allocation, reference to a freed block, or an unclaimed log block.
6430 	 *
6431 	 * When leak detection is disabled (-L option) we still traverse the
6432 	 * pool claiming each block we discover, but we skip opening any space
6433 	 * maps.
6434 	 */
6435 	zdb_leak_init(spa, &zcb);
6436 
6437 	/*
6438 	 * If there's a deferred-free bplist, process that first.
6439 	 */
6440 	(void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
6441 	    bpobj_count_block_cb, &zcb, NULL);
6442 
6443 	if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
6444 		(void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
6445 		    bpobj_count_block_cb, &zcb, NULL);
6446 	}
6447 
6448 	zdb_claim_removing(spa, &zcb);
6449 
6450 	if (spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
6451 		VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
6452 		    spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
6453 		    &zcb, NULL));
6454 	}
6455 
6456 	deleted_livelists_count_blocks(spa, &zcb);
6457 
6458 	if (dump_opt['c'] > 1)
6459 		flags |= TRAVERSE_PREFETCH_DATA;
6460 
6461 	zcb.zcb_totalasize = metaslab_class_get_alloc(spa_normal_class(spa));
6462 	zcb.zcb_totalasize += metaslab_class_get_alloc(spa_special_class(spa));
6463 	zcb.zcb_totalasize += metaslab_class_get_alloc(spa_dedup_class(spa));
6464 	zcb.zcb_totalasize +=
6465 	    metaslab_class_get_alloc(spa_embedded_log_class(spa));
6466 	zcb.zcb_start = zcb.zcb_lastprint = gethrtime();
6467 	err = traverse_pool(spa, 0, flags, zdb_blkptr_cb, &zcb);
6468 
6469 	/*
6470 	 * If we've traversed the data blocks then we need to wait for those
6471 	 * I/Os to complete. We leverage "The Godfather" zio to wait on
6472 	 * all async I/Os to complete.
6473 	 */
6474 	if (dump_opt['c']) {
6475 		for (c = 0; c < max_ncpus; c++) {
6476 			(void) zio_wait(spa->spa_async_zio_root[c]);
6477 			spa->spa_async_zio_root[c] = zio_root(spa, NULL, NULL,
6478 			    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
6479 			    ZIO_FLAG_GODFATHER);
6480 		}
6481 	}
6482 	ASSERT0(spa->spa_load_verify_bytes);
6483 
6484 	/*
6485 	 * Done after zio_wait() since zcb_haderrors is modified in
6486 	 * zdb_blkptr_done()
6487 	 */
6488 	zcb.zcb_haderrors |= err;
6489 
6490 	if (zcb.zcb_haderrors) {
6491 		(void) printf("\nError counts:\n\n");
6492 		(void) printf("\t%5s  %s\n", "errno", "count");
6493 		for (e = 0; e < 256; e++) {
6494 			if (zcb.zcb_errors[e] != 0) {
6495 				(void) printf("\t%5d  %llu\n",
6496 				    e, (u_longlong_t)zcb.zcb_errors[e]);
6497 			}
6498 		}
6499 	}
6500 
6501 	/*
6502 	 * Report any leaked segments.
6503 	 */
6504 	leaks |= zdb_leak_fini(spa, &zcb);
6505 
6506 	tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
6507 
6508 	norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
6509 	norm_space = metaslab_class_get_space(spa_normal_class(spa));
6510 
6511 	total_alloc = norm_alloc +
6512 	    metaslab_class_get_alloc(spa_log_class(spa)) +
6513 	    metaslab_class_get_alloc(spa_embedded_log_class(spa)) +
6514 	    metaslab_class_get_alloc(spa_special_class(spa)) +
6515 	    metaslab_class_get_alloc(spa_dedup_class(spa)) +
6516 	    get_unflushed_alloc_space(spa);
6517 	total_found = tzb->zb_asize - zcb.zcb_dedup_asize +
6518 	    zcb.zcb_removing_size + zcb.zcb_checkpoint_size;
6519 
6520 	if (total_found == total_alloc && !dump_opt['L']) {
6521 		(void) printf("\n\tNo leaks (block sum matches space"
6522 		    " maps exactly)\n");
6523 	} else if (!dump_opt['L']) {
6524 		(void) printf("block traversal size %llu != alloc %llu "
6525 		    "(%s %lld)\n",
6526 		    (u_longlong_t)total_found,
6527 		    (u_longlong_t)total_alloc,
6528 		    (dump_opt['L']) ? "unreachable" : "leaked",
6529 		    (longlong_t)(total_alloc - total_found));
6530 		leaks = B_TRUE;
6531 	}
6532 
6533 	if (tzb->zb_count == 0)
6534 		return (2);
6535 
6536 	(void) printf("\n");
6537 	(void) printf("\t%-16s %14llu\n", "bp count:",
6538 	    (u_longlong_t)tzb->zb_count);
6539 	(void) printf("\t%-16s %14llu\n", "ganged count:",
6540 	    (longlong_t)tzb->zb_gangs);
6541 	(void) printf("\t%-16s %14llu      avg: %6llu\n", "bp logical:",
6542 	    (u_longlong_t)tzb->zb_lsize,
6543 	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
6544 	(void) printf("\t%-16s %14llu      avg: %6llu     compression: %6.2f\n",
6545 	    "bp physical:", (u_longlong_t)tzb->zb_psize,
6546 	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
6547 	    (double)tzb->zb_lsize / tzb->zb_psize);
6548 	(void) printf("\t%-16s %14llu      avg: %6llu     compression: %6.2f\n",
6549 	    "bp allocated:", (u_longlong_t)tzb->zb_asize,
6550 	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
6551 	    (double)tzb->zb_lsize / tzb->zb_asize);
6552 	(void) printf("\t%-16s %14llu    ref>1: %6llu   deduplication: %6.2f\n",
6553 	    "bp deduped:", (u_longlong_t)zcb.zcb_dedup_asize,
6554 	    (u_longlong_t)zcb.zcb_dedup_blocks,
6555 	    (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
6556 	(void) printf("\t%-16s %14llu     used: %5.2f%%\n", "Normal class:",
6557 	    (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
6558 
6559 	if (spa_special_class(spa)->mc_allocator[0].mca_rotor != NULL) {
6560 		uint64_t alloc = metaslab_class_get_alloc(
6561 		    spa_special_class(spa));
6562 		uint64_t space = metaslab_class_get_space(
6563 		    spa_special_class(spa));
6564 
6565 		(void) printf("\t%-16s %14llu     used: %5.2f%%\n",
6566 		    "Special class", (u_longlong_t)alloc,
6567 		    100.0 * alloc / space);
6568 	}
6569 
6570 	if (spa_dedup_class(spa)->mc_allocator[0].mca_rotor != NULL) {
6571 		uint64_t alloc = metaslab_class_get_alloc(
6572 		    spa_dedup_class(spa));
6573 		uint64_t space = metaslab_class_get_space(
6574 		    spa_dedup_class(spa));
6575 
6576 		(void) printf("\t%-16s %14llu     used: %5.2f%%\n",
6577 		    "Dedup class", (u_longlong_t)alloc,
6578 		    100.0 * alloc / space);
6579 	}
6580 
6581 	if (spa_embedded_log_class(spa)->mc_allocator[0].mca_rotor != NULL) {
6582 		uint64_t alloc = metaslab_class_get_alloc(
6583 		    spa_embedded_log_class(spa));
6584 		uint64_t space = metaslab_class_get_space(
6585 		    spa_embedded_log_class(spa));
6586 
6587 		(void) printf("\t%-16s %14llu     used: %5.2f%%\n",
6588 		    "Embedded log class", (u_longlong_t)alloc,
6589 		    100.0 * alloc / space);
6590 	}
6591 
6592 	for (i = 0; i < NUM_BP_EMBEDDED_TYPES; i++) {
6593 		if (zcb.zcb_embedded_blocks[i] == 0)
6594 			continue;
6595 		(void) printf("\n");
6596 		(void) printf("\tadditional, non-pointer bps of type %u: "
6597 		    "%10llu\n",
6598 		    i, (u_longlong_t)zcb.zcb_embedded_blocks[i]);
6599 
6600 		if (dump_opt['b'] >= 3) {
6601 			(void) printf("\t number of (compressed) bytes:  "
6602 			    "number of bps\n");
6603 			dump_histogram(zcb.zcb_embedded_histogram[i],
6604 			    sizeof (zcb.zcb_embedded_histogram[i]) /
6605 			    sizeof (zcb.zcb_embedded_histogram[i][0]), 0);
6606 		}
6607 	}
6608 
6609 	if (tzb->zb_ditto_samevdev != 0) {
6610 		(void) printf("\tDittoed blocks on same vdev: %llu\n",
6611 		    (longlong_t)tzb->zb_ditto_samevdev);
6612 	}
6613 	if (tzb->zb_ditto_same_ms != 0) {
6614 		(void) printf("\tDittoed blocks in same metaslab: %llu\n",
6615 		    (longlong_t)tzb->zb_ditto_same_ms);
6616 	}
6617 
6618 	for (uint64_t v = 0; v < spa->spa_root_vdev->vdev_children; v++) {
6619 		vdev_t *vd = spa->spa_root_vdev->vdev_child[v];
6620 		vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
6621 
6622 		if (vim == NULL) {
6623 			continue;
6624 		}
6625 
6626 		char mem[32];
6627 		zdb_nicenum(vdev_indirect_mapping_num_entries(vim),
6628 		    mem, vdev_indirect_mapping_size(vim));
6629 
6630 		(void) printf("\tindirect vdev id %llu has %llu segments "
6631 		    "(%s in memory)\n",
6632 		    (longlong_t)vd->vdev_id,
6633 		    (longlong_t)vdev_indirect_mapping_num_entries(vim), mem);
6634 	}
6635 
6636 	if (dump_opt['b'] >= 2) {
6637 		int l, t, level;
6638 		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
6639 		    "\t  avg\t comp\t%%Total\tType\n");
6640 
6641 		for (t = 0; t <= ZDB_OT_TOTAL; t++) {
6642 			char csize[32], lsize[32], psize[32], asize[32];
6643 			char avg[32], gang[32];
6644 			const char *typename;
6645 
6646 			/* make sure nicenum has enough space */
6647 			_Static_assert(sizeof (csize) >= NN_NUMBUF_SZ,
6648 			    "csize truncated");
6649 			_Static_assert(sizeof (lsize) >= NN_NUMBUF_SZ,
6650 			    "lsize truncated");
6651 			_Static_assert(sizeof (psize) >= NN_NUMBUF_SZ,
6652 			    "psize truncated");
6653 			_Static_assert(sizeof (asize) >= NN_NUMBUF_SZ,
6654 			    "asize truncated");
6655 			_Static_assert(sizeof (avg) >= NN_NUMBUF_SZ,
6656 			    "avg truncated");
6657 			_Static_assert(sizeof (gang) >= NN_NUMBUF_SZ,
6658 			    "gang truncated");
6659 
6660 			if (t < DMU_OT_NUMTYPES)
6661 				typename = dmu_ot[t].ot_name;
6662 			else
6663 				typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
6664 
6665 			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
6666 				(void) printf("%6s\t%5s\t%5s\t%5s"
6667 				    "\t%5s\t%5s\t%6s\t%s\n",
6668 				    "-",
6669 				    "-",
6670 				    "-",
6671 				    "-",
6672 				    "-",
6673 				    "-",
6674 				    "-",
6675 				    typename);
6676 				continue;
6677 			}
6678 
6679 			for (l = ZB_TOTAL - 1; l >= -1; l--) {
6680 				level = (l == -1 ? ZB_TOTAL : l);
6681 				zb = &zcb.zcb_type[level][t];
6682 
6683 				if (zb->zb_asize == 0)
6684 					continue;
6685 
6686 				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
6687 					continue;
6688 
6689 				if (level == 0 && zb->zb_asize ==
6690 				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
6691 					continue;
6692 
6693 				zdb_nicenum(zb->zb_count, csize,
6694 				    sizeof (csize));
6695 				zdb_nicenum(zb->zb_lsize, lsize,
6696 				    sizeof (lsize));
6697 				zdb_nicenum(zb->zb_psize, psize,
6698 				    sizeof (psize));
6699 				zdb_nicenum(zb->zb_asize, asize,
6700 				    sizeof (asize));
6701 				zdb_nicenum(zb->zb_asize / zb->zb_count, avg,
6702 				    sizeof (avg));
6703 				zdb_nicenum(zb->zb_gangs, gang, sizeof (gang));
6704 
6705 				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
6706 				    "\t%5.2f\t%6.2f\t",
6707 				    csize, lsize, psize, asize, avg,
6708 				    (double)zb->zb_lsize / zb->zb_psize,
6709 				    100.0 * zb->zb_asize / tzb->zb_asize);
6710 
6711 				if (level == ZB_TOTAL)
6712 					(void) printf("%s\n", typename);
6713 				else
6714 					(void) printf("    L%d %s\n",
6715 					    level, typename);
6716 
6717 				if (dump_opt['b'] >= 3 && zb->zb_gangs > 0) {
6718 					(void) printf("\t number of ganged "
6719 					    "blocks: %s\n", gang);
6720 				}
6721 
6722 				if (dump_opt['b'] >= 4) {
6723 					(void) printf("psize "
6724 					    "(in 512-byte sectors): "
6725 					    "number of blocks\n");
6726 					dump_histogram(zb->zb_psize_histogram,
6727 					    PSIZE_HISTO_SIZE, 0);
6728 				}
6729 			}
6730 		}
6731 
6732 		/* Output a table summarizing block sizes in the pool */
6733 		if (dump_opt['b'] >= 2) {
6734 			dump_size_histograms(&zcb);
6735 		}
6736 	}
6737 
6738 	(void) printf("\n");
6739 
6740 	if (leaks)
6741 		return (2);
6742 
6743 	if (zcb.zcb_haderrors)
6744 		return (3);
6745 
6746 	return (0);
6747 }
6748 
6749 typedef struct zdb_ddt_entry {
6750 	ddt_key_t	zdde_key;
6751 	uint64_t	zdde_ref_blocks;
6752 	uint64_t	zdde_ref_lsize;
6753 	uint64_t	zdde_ref_psize;
6754 	uint64_t	zdde_ref_dsize;
6755 	avl_node_t	zdde_node;
6756 } zdb_ddt_entry_t;
6757 
6758 static int
6759 zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
6760     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
6761 {
6762 	(void) zilog, (void) dnp;
6763 	avl_tree_t *t = arg;
6764 	avl_index_t where;
6765 	zdb_ddt_entry_t *zdde, zdde_search;
6766 
6767 	if (zb->zb_level == ZB_DNODE_LEVEL || BP_IS_HOLE(bp) ||
6768 	    BP_IS_EMBEDDED(bp))
6769 		return (0);
6770 
6771 	if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
6772 		(void) printf("traversing objset %llu, %llu objects, "
6773 		    "%lu blocks so far\n",
6774 		    (u_longlong_t)zb->zb_objset,
6775 		    (u_longlong_t)BP_GET_FILL(bp),
6776 		    avl_numnodes(t));
6777 	}
6778 
6779 	if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
6780 	    BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
6781 		return (0);
6782 
6783 	ddt_key_fill(&zdde_search.zdde_key, bp);
6784 
6785 	zdde = avl_find(t, &zdde_search, &where);
6786 
6787 	if (zdde == NULL) {
6788 		zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
6789 		zdde->zdde_key = zdde_search.zdde_key;
6790 		avl_insert(t, zdde, where);
6791 	}
6792 
6793 	zdde->zdde_ref_blocks += 1;
6794 	zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
6795 	zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
6796 	zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
6797 
6798 	return (0);
6799 }
6800 
6801 static void
6802 dump_simulated_ddt(spa_t *spa)
6803 {
6804 	avl_tree_t t;
6805 	void *cookie = NULL;
6806 	zdb_ddt_entry_t *zdde;
6807 	ddt_histogram_t ddh_total = {{{0}}};
6808 	ddt_stat_t dds_total = {0};
6809 
6810 	avl_create(&t, ddt_entry_compare,
6811 	    sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
6812 
6813 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6814 
6815 	(void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
6816 	    TRAVERSE_NO_DECRYPT, zdb_ddt_add_cb, &t);
6817 
6818 	spa_config_exit(spa, SCL_CONFIG, FTAG);
6819 
6820 	while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
6821 		ddt_stat_t dds;
6822 		uint64_t refcnt = zdde->zdde_ref_blocks;
6823 		ASSERT(refcnt != 0);
6824 
6825 		dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
6826 		dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
6827 		dds.dds_psize = zdde->zdde_ref_psize / refcnt;
6828 		dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
6829 
6830 		dds.dds_ref_blocks = zdde->zdde_ref_blocks;
6831 		dds.dds_ref_lsize = zdde->zdde_ref_lsize;
6832 		dds.dds_ref_psize = zdde->zdde_ref_psize;
6833 		dds.dds_ref_dsize = zdde->zdde_ref_dsize;
6834 
6835 		ddt_stat_add(&ddh_total.ddh_stat[highbit64(refcnt) - 1],
6836 		    &dds, 0);
6837 
6838 		umem_free(zdde, sizeof (*zdde));
6839 	}
6840 
6841 	avl_destroy(&t);
6842 
6843 	ddt_histogram_stat(&dds_total, &ddh_total);
6844 
6845 	(void) printf("Simulated DDT histogram:\n");
6846 
6847 	zpool_dump_ddt(&dds_total, &ddh_total);
6848 
6849 	dump_dedup_ratio(&dds_total);
6850 }
6851 
6852 static int
6853 verify_device_removal_feature_counts(spa_t *spa)
6854 {
6855 	uint64_t dr_feature_refcount = 0;
6856 	uint64_t oc_feature_refcount = 0;
6857 	uint64_t indirect_vdev_count = 0;
6858 	uint64_t precise_vdev_count = 0;
6859 	uint64_t obsolete_counts_object_count = 0;
6860 	uint64_t obsolete_sm_count = 0;
6861 	uint64_t obsolete_counts_count = 0;
6862 	uint64_t scip_count = 0;
6863 	uint64_t obsolete_bpobj_count = 0;
6864 	int ret = 0;
6865 
6866 	spa_condensing_indirect_phys_t *scip =
6867 	    &spa->spa_condensing_indirect_phys;
6868 	if (scip->scip_next_mapping_object != 0) {
6869 		vdev_t *vd = spa->spa_root_vdev->vdev_child[scip->scip_vdev];
6870 		ASSERT(scip->scip_prev_obsolete_sm_object != 0);
6871 		ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
6872 
6873 		(void) printf("Condensing indirect vdev %llu: new mapping "
6874 		    "object %llu, prev obsolete sm %llu\n",
6875 		    (u_longlong_t)scip->scip_vdev,
6876 		    (u_longlong_t)scip->scip_next_mapping_object,
6877 		    (u_longlong_t)scip->scip_prev_obsolete_sm_object);
6878 		if (scip->scip_prev_obsolete_sm_object != 0) {
6879 			space_map_t *prev_obsolete_sm = NULL;
6880 			VERIFY0(space_map_open(&prev_obsolete_sm,
6881 			    spa->spa_meta_objset,
6882 			    scip->scip_prev_obsolete_sm_object,
6883 			    0, vd->vdev_asize, 0));
6884 			dump_spacemap(spa->spa_meta_objset, prev_obsolete_sm);
6885 			(void) printf("\n");
6886 			space_map_close(prev_obsolete_sm);
6887 		}
6888 
6889 		scip_count += 2;
6890 	}
6891 
6892 	for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
6893 		vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
6894 		vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
6895 
6896 		if (vic->vic_mapping_object != 0) {
6897 			ASSERT(vd->vdev_ops == &vdev_indirect_ops ||
6898 			    vd->vdev_removing);
6899 			indirect_vdev_count++;
6900 
6901 			if (vd->vdev_indirect_mapping->vim_havecounts) {
6902 				obsolete_counts_count++;
6903 			}
6904 		}
6905 
6906 		boolean_t are_precise;
6907 		VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
6908 		if (are_precise) {
6909 			ASSERT(vic->vic_mapping_object != 0);
6910 			precise_vdev_count++;
6911 		}
6912 
6913 		uint64_t obsolete_sm_object;
6914 		VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
6915 		if (obsolete_sm_object != 0) {
6916 			ASSERT(vic->vic_mapping_object != 0);
6917 			obsolete_sm_count++;
6918 		}
6919 	}
6920 
6921 	(void) feature_get_refcount(spa,
6922 	    &spa_feature_table[SPA_FEATURE_DEVICE_REMOVAL],
6923 	    &dr_feature_refcount);
6924 	(void) feature_get_refcount(spa,
6925 	    &spa_feature_table[SPA_FEATURE_OBSOLETE_COUNTS],
6926 	    &oc_feature_refcount);
6927 
6928 	if (dr_feature_refcount != indirect_vdev_count) {
6929 		ret = 1;
6930 		(void) printf("Number of indirect vdevs (%llu) " \
6931 		    "does not match feature count (%llu)\n",
6932 		    (u_longlong_t)indirect_vdev_count,
6933 		    (u_longlong_t)dr_feature_refcount);
6934 	} else {
6935 		(void) printf("Verified device_removal feature refcount " \
6936 		    "of %llu is correct\n",
6937 		    (u_longlong_t)dr_feature_refcount);
6938 	}
6939 
6940 	if (zap_contains(spa_meta_objset(spa), DMU_POOL_DIRECTORY_OBJECT,
6941 	    DMU_POOL_OBSOLETE_BPOBJ) == 0) {
6942 		obsolete_bpobj_count++;
6943 	}
6944 
6945 
6946 	obsolete_counts_object_count = precise_vdev_count;
6947 	obsolete_counts_object_count += obsolete_sm_count;
6948 	obsolete_counts_object_count += obsolete_counts_count;
6949 	obsolete_counts_object_count += scip_count;
6950 	obsolete_counts_object_count += obsolete_bpobj_count;
6951 	obsolete_counts_object_count += remap_deadlist_count;
6952 
6953 	if (oc_feature_refcount != obsolete_counts_object_count) {
6954 		ret = 1;
6955 		(void) printf("Number of obsolete counts objects (%llu) " \
6956 		    "does not match feature count (%llu)\n",
6957 		    (u_longlong_t)obsolete_counts_object_count,
6958 		    (u_longlong_t)oc_feature_refcount);
6959 		(void) printf("pv:%llu os:%llu oc:%llu sc:%llu "
6960 		    "ob:%llu rd:%llu\n",
6961 		    (u_longlong_t)precise_vdev_count,
6962 		    (u_longlong_t)obsolete_sm_count,
6963 		    (u_longlong_t)obsolete_counts_count,
6964 		    (u_longlong_t)scip_count,
6965 		    (u_longlong_t)obsolete_bpobj_count,
6966 		    (u_longlong_t)remap_deadlist_count);
6967 	} else {
6968 		(void) printf("Verified indirect_refcount feature refcount " \
6969 		    "of %llu is correct\n",
6970 		    (u_longlong_t)oc_feature_refcount);
6971 	}
6972 	return (ret);
6973 }
6974 
6975 static void
6976 zdb_set_skip_mmp(char *target)
6977 {
6978 	spa_t *spa;
6979 
6980 	/*
6981 	 * Disable the activity check to allow examination of
6982 	 * active pools.
6983 	 */
6984 	mutex_enter(&spa_namespace_lock);
6985 	if ((spa = spa_lookup(target)) != NULL) {
6986 		spa->spa_import_flags |= ZFS_IMPORT_SKIP_MMP;
6987 	}
6988 	mutex_exit(&spa_namespace_lock);
6989 }
6990 
6991 #define	BOGUS_SUFFIX "_CHECKPOINTED_UNIVERSE"
6992 /*
6993  * Import the checkpointed state of the pool specified by the target
6994  * parameter as readonly. The function also accepts a pool config
6995  * as an optional parameter, else it attempts to infer the config by
6996  * the name of the target pool.
6997  *
6998  * Note that the checkpointed state's pool name will be the name of
6999  * the original pool with the above suffix appended to it. In addition,
7000  * if the target is not a pool name (e.g. a path to a dataset) then
7001  * the new_path parameter is populated with the updated path to
7002  * reflect the fact that we are looking into the checkpointed state.
7003  *
7004  * The function returns a newly-allocated copy of the name of the
7005  * pool containing the checkpointed state. When this copy is no
7006  * longer needed it should be freed with free(3C). Same thing
7007  * applies to the new_path parameter if allocated.
7008  */
7009 static char *
7010 import_checkpointed_state(char *target, nvlist_t *cfg, char **new_path)
7011 {
7012 	int error = 0;
7013 	char *poolname, *bogus_name = NULL;
7014 	boolean_t freecfg = B_FALSE;
7015 
7016 	/* If the target is not a pool, the extract the pool name */
7017 	char *path_start = strchr(target, '/');
7018 	if (path_start != NULL) {
7019 		size_t poolname_len = path_start - target;
7020 		poolname = strndup(target, poolname_len);
7021 	} else {
7022 		poolname = target;
7023 	}
7024 
7025 	if (cfg == NULL) {
7026 		zdb_set_skip_mmp(poolname);
7027 		error = spa_get_stats(poolname, &cfg, NULL, 0);
7028 		if (error != 0) {
7029 			fatal("Tried to read config of pool \"%s\" but "
7030 			    "spa_get_stats() failed with error %d\n",
7031 			    poolname, error);
7032 		}
7033 		freecfg = B_TRUE;
7034 	}
7035 
7036 	if (asprintf(&bogus_name, "%s%s", poolname, BOGUS_SUFFIX) == -1)
7037 		return (NULL);
7038 	fnvlist_add_string(cfg, ZPOOL_CONFIG_POOL_NAME, bogus_name);
7039 
7040 	error = spa_import(bogus_name, cfg, NULL,
7041 	    ZFS_IMPORT_MISSING_LOG | ZFS_IMPORT_CHECKPOINT |
7042 	    ZFS_IMPORT_SKIP_MMP);
7043 	if (freecfg)
7044 		nvlist_free(cfg);
7045 	if (error != 0) {
7046 		fatal("Tried to import pool \"%s\" but spa_import() failed "
7047 		    "with error %d\n", bogus_name, error);
7048 	}
7049 
7050 	if (new_path != NULL && path_start != NULL) {
7051 		if (asprintf(new_path, "%s%s", bogus_name, path_start) == -1) {
7052 			if (path_start != NULL)
7053 				free(poolname);
7054 			return (NULL);
7055 		}
7056 	}
7057 
7058 	if (target != poolname)
7059 		free(poolname);
7060 
7061 	return (bogus_name);
7062 }
7063 
7064 typedef struct verify_checkpoint_sm_entry_cb_arg {
7065 	vdev_t *vcsec_vd;
7066 
7067 	/* the following fields are only used for printing progress */
7068 	uint64_t vcsec_entryid;
7069 	uint64_t vcsec_num_entries;
7070 } verify_checkpoint_sm_entry_cb_arg_t;
7071 
7072 #define	ENTRIES_PER_PROGRESS_UPDATE 10000
7073 
7074 static int
7075 verify_checkpoint_sm_entry_cb(space_map_entry_t *sme, void *arg)
7076 {
7077 	verify_checkpoint_sm_entry_cb_arg_t *vcsec = arg;
7078 	vdev_t *vd = vcsec->vcsec_vd;
7079 	metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
7080 	uint64_t end = sme->sme_offset + sme->sme_run;
7081 
7082 	ASSERT(sme->sme_type == SM_FREE);
7083 
7084 	if ((vcsec->vcsec_entryid % ENTRIES_PER_PROGRESS_UPDATE) == 0) {
7085 		(void) fprintf(stderr,
7086 		    "\rverifying vdev %llu, space map entry %llu of %llu ...",
7087 		    (longlong_t)vd->vdev_id,
7088 		    (longlong_t)vcsec->vcsec_entryid,
7089 		    (longlong_t)vcsec->vcsec_num_entries);
7090 	}
7091 	vcsec->vcsec_entryid++;
7092 
7093 	/*
7094 	 * See comment in checkpoint_sm_exclude_entry_cb()
7095 	 */
7096 	VERIFY3U(sme->sme_offset, >=, ms->ms_start);
7097 	VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
7098 
7099 	/*
7100 	 * The entries in the vdev_checkpoint_sm should be marked as
7101 	 * allocated in the checkpointed state of the pool, therefore
7102 	 * their respective ms_allocateable trees should not contain them.
7103 	 */
7104 	mutex_enter(&ms->ms_lock);
7105 	range_tree_verify_not_present(ms->ms_allocatable,
7106 	    sme->sme_offset, sme->sme_run);
7107 	mutex_exit(&ms->ms_lock);
7108 
7109 	return (0);
7110 }
7111 
7112 /*
7113  * Verify that all segments in the vdev_checkpoint_sm are allocated
7114  * according to the checkpoint's ms_sm (i.e. are not in the checkpoint's
7115  * ms_allocatable).
7116  *
7117  * Do so by comparing the checkpoint space maps (vdev_checkpoint_sm) of
7118  * each vdev in the current state of the pool to the metaslab space maps
7119  * (ms_sm) of the checkpointed state of the pool.
7120  *
7121  * Note that the function changes the state of the ms_allocatable
7122  * trees of the current spa_t. The entries of these ms_allocatable
7123  * trees are cleared out and then repopulated from with the free
7124  * entries of their respective ms_sm space maps.
7125  */
7126 static void
7127 verify_checkpoint_vdev_spacemaps(spa_t *checkpoint, spa_t *current)
7128 {
7129 	vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
7130 	vdev_t *current_rvd = current->spa_root_vdev;
7131 
7132 	load_concrete_ms_allocatable_trees(checkpoint, SM_FREE);
7133 
7134 	for (uint64_t c = 0; c < ckpoint_rvd->vdev_children; c++) {
7135 		vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[c];
7136 		vdev_t *current_vd = current_rvd->vdev_child[c];
7137 
7138 		space_map_t *checkpoint_sm = NULL;
7139 		uint64_t checkpoint_sm_obj;
7140 
7141 		if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
7142 			/*
7143 			 * Since we don't allow device removal in a pool
7144 			 * that has a checkpoint, we expect that all removed
7145 			 * vdevs were removed from the pool before the
7146 			 * checkpoint.
7147 			 */
7148 			ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
7149 			continue;
7150 		}
7151 
7152 		/*
7153 		 * If the checkpoint space map doesn't exist, then nothing
7154 		 * here is checkpointed so there's nothing to verify.
7155 		 */
7156 		if (current_vd->vdev_top_zap == 0 ||
7157 		    zap_contains(spa_meta_objset(current),
7158 		    current_vd->vdev_top_zap,
7159 		    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
7160 			continue;
7161 
7162 		VERIFY0(zap_lookup(spa_meta_objset(current),
7163 		    current_vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
7164 		    sizeof (uint64_t), 1, &checkpoint_sm_obj));
7165 
7166 		VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(current),
7167 		    checkpoint_sm_obj, 0, current_vd->vdev_asize,
7168 		    current_vd->vdev_ashift));
7169 
7170 		verify_checkpoint_sm_entry_cb_arg_t vcsec;
7171 		vcsec.vcsec_vd = ckpoint_vd;
7172 		vcsec.vcsec_entryid = 0;
7173 		vcsec.vcsec_num_entries =
7174 		    space_map_length(checkpoint_sm) / sizeof (uint64_t);
7175 		VERIFY0(space_map_iterate(checkpoint_sm,
7176 		    space_map_length(checkpoint_sm),
7177 		    verify_checkpoint_sm_entry_cb, &vcsec));
7178 		if (dump_opt['m'] > 3)
7179 			dump_spacemap(current->spa_meta_objset, checkpoint_sm);
7180 		space_map_close(checkpoint_sm);
7181 	}
7182 
7183 	/*
7184 	 * If we've added vdevs since we took the checkpoint, ensure
7185 	 * that their checkpoint space maps are empty.
7186 	 */
7187 	if (ckpoint_rvd->vdev_children < current_rvd->vdev_children) {
7188 		for (uint64_t c = ckpoint_rvd->vdev_children;
7189 		    c < current_rvd->vdev_children; c++) {
7190 			vdev_t *current_vd = current_rvd->vdev_child[c];
7191 			VERIFY3P(current_vd->vdev_checkpoint_sm, ==, NULL);
7192 		}
7193 	}
7194 
7195 	/* for cleaner progress output */
7196 	(void) fprintf(stderr, "\n");
7197 }
7198 
7199 /*
7200  * Verifies that all space that's allocated in the checkpoint is
7201  * still allocated in the current version, by checking that everything
7202  * in checkpoint's ms_allocatable (which is actually allocated, not
7203  * allocatable/free) is not present in current's ms_allocatable.
7204  *
7205  * Note that the function changes the state of the ms_allocatable
7206  * trees of both spas when called. The entries of all ms_allocatable
7207  * trees are cleared out and then repopulated from their respective
7208  * ms_sm space maps. In the checkpointed state we load the allocated
7209  * entries, and in the current state we load the free entries.
7210  */
7211 static void
7212 verify_checkpoint_ms_spacemaps(spa_t *checkpoint, spa_t *current)
7213 {
7214 	vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
7215 	vdev_t *current_rvd = current->spa_root_vdev;
7216 
7217 	load_concrete_ms_allocatable_trees(checkpoint, SM_ALLOC);
7218 	load_concrete_ms_allocatable_trees(current, SM_FREE);
7219 
7220 	for (uint64_t i = 0; i < ckpoint_rvd->vdev_children; i++) {
7221 		vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[i];
7222 		vdev_t *current_vd = current_rvd->vdev_child[i];
7223 
7224 		if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
7225 			/*
7226 			 * See comment in verify_checkpoint_vdev_spacemaps()
7227 			 */
7228 			ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
7229 			continue;
7230 		}
7231 
7232 		for (uint64_t m = 0; m < ckpoint_vd->vdev_ms_count; m++) {
7233 			metaslab_t *ckpoint_msp = ckpoint_vd->vdev_ms[m];
7234 			metaslab_t *current_msp = current_vd->vdev_ms[m];
7235 
7236 			(void) fprintf(stderr,
7237 			    "\rverifying vdev %llu of %llu, "
7238 			    "metaslab %llu of %llu ...",
7239 			    (longlong_t)current_vd->vdev_id,
7240 			    (longlong_t)current_rvd->vdev_children,
7241 			    (longlong_t)current_vd->vdev_ms[m]->ms_id,
7242 			    (longlong_t)current_vd->vdev_ms_count);
7243 
7244 			/*
7245 			 * We walk through the ms_allocatable trees that
7246 			 * are loaded with the allocated blocks from the
7247 			 * ms_sm spacemaps of the checkpoint. For each
7248 			 * one of these ranges we ensure that none of them
7249 			 * exists in the ms_allocatable trees of the
7250 			 * current state which are loaded with the ranges
7251 			 * that are currently free.
7252 			 *
7253 			 * This way we ensure that none of the blocks that
7254 			 * are part of the checkpoint were freed by mistake.
7255 			 */
7256 			range_tree_walk(ckpoint_msp->ms_allocatable,
7257 			    (range_tree_func_t *)range_tree_verify_not_present,
7258 			    current_msp->ms_allocatable);
7259 		}
7260 	}
7261 
7262 	/* for cleaner progress output */
7263 	(void) fprintf(stderr, "\n");
7264 }
7265 
7266 static void
7267 verify_checkpoint_blocks(spa_t *spa)
7268 {
7269 	ASSERT(!dump_opt['L']);
7270 
7271 	spa_t *checkpoint_spa;
7272 	char *checkpoint_pool;
7273 	int error = 0;
7274 
7275 	/*
7276 	 * We import the checkpointed state of the pool (under a different
7277 	 * name) so we can do verification on it against the current state
7278 	 * of the pool.
7279 	 */
7280 	checkpoint_pool = import_checkpointed_state(spa->spa_name, NULL,
7281 	    NULL);
7282 	ASSERT(strcmp(spa->spa_name, checkpoint_pool) != 0);
7283 
7284 	error = spa_open(checkpoint_pool, &checkpoint_spa, FTAG);
7285 	if (error != 0) {
7286 		fatal("Tried to open pool \"%s\" but spa_open() failed with "
7287 		    "error %d\n", checkpoint_pool, error);
7288 	}
7289 
7290 	/*
7291 	 * Ensure that ranges in the checkpoint space maps of each vdev
7292 	 * are allocated according to the checkpointed state's metaslab
7293 	 * space maps.
7294 	 */
7295 	verify_checkpoint_vdev_spacemaps(checkpoint_spa, spa);
7296 
7297 	/*
7298 	 * Ensure that allocated ranges in the checkpoint's metaslab
7299 	 * space maps remain allocated in the metaslab space maps of
7300 	 * the current state.
7301 	 */
7302 	verify_checkpoint_ms_spacemaps(checkpoint_spa, spa);
7303 
7304 	/*
7305 	 * Once we are done, we get rid of the checkpointed state.
7306 	 */
7307 	spa_close(checkpoint_spa, FTAG);
7308 	free(checkpoint_pool);
7309 }
7310 
7311 static void
7312 dump_leftover_checkpoint_blocks(spa_t *spa)
7313 {
7314 	vdev_t *rvd = spa->spa_root_vdev;
7315 
7316 	for (uint64_t i = 0; i < rvd->vdev_children; i++) {
7317 		vdev_t *vd = rvd->vdev_child[i];
7318 
7319 		space_map_t *checkpoint_sm = NULL;
7320 		uint64_t checkpoint_sm_obj;
7321 
7322 		if (vd->vdev_top_zap == 0)
7323 			continue;
7324 
7325 		if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
7326 		    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
7327 			continue;
7328 
7329 		VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
7330 		    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
7331 		    sizeof (uint64_t), 1, &checkpoint_sm_obj));
7332 
7333 		VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
7334 		    checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
7335 		dump_spacemap(spa->spa_meta_objset, checkpoint_sm);
7336 		space_map_close(checkpoint_sm);
7337 	}
7338 }
7339 
7340 static int
7341 verify_checkpoint(spa_t *spa)
7342 {
7343 	uberblock_t checkpoint;
7344 	int error;
7345 
7346 	if (!spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT))
7347 		return (0);
7348 
7349 	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7350 	    DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
7351 	    sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
7352 
7353 	if (error == ENOENT && !dump_opt['L']) {
7354 		/*
7355 		 * If the feature is active but the uberblock is missing
7356 		 * then we must be in the middle of discarding the
7357 		 * checkpoint.
7358 		 */
7359 		(void) printf("\nPartially discarded checkpoint "
7360 		    "state found:\n");
7361 		if (dump_opt['m'] > 3)
7362 			dump_leftover_checkpoint_blocks(spa);
7363 		return (0);
7364 	} else if (error != 0) {
7365 		(void) printf("lookup error %d when looking for "
7366 		    "checkpointed uberblock in MOS\n", error);
7367 		return (error);
7368 	}
7369 	dump_uberblock(&checkpoint, "\nCheckpointed uberblock found:\n", "\n");
7370 
7371 	if (checkpoint.ub_checkpoint_txg == 0) {
7372 		(void) printf("\nub_checkpoint_txg not set in checkpointed "
7373 		    "uberblock\n");
7374 		error = 3;
7375 	}
7376 
7377 	if (error == 0 && !dump_opt['L'])
7378 		verify_checkpoint_blocks(spa);
7379 
7380 	return (error);
7381 }
7382 
7383 static void
7384 mos_leaks_cb(void *arg, uint64_t start, uint64_t size)
7385 {
7386 	(void) arg;
7387 	for (uint64_t i = start; i < size; i++) {
7388 		(void) printf("MOS object %llu referenced but not allocated\n",
7389 		    (u_longlong_t)i);
7390 	}
7391 }
7392 
7393 static void
7394 mos_obj_refd(uint64_t obj)
7395 {
7396 	if (obj != 0 && mos_refd_objs != NULL)
7397 		range_tree_add(mos_refd_objs, obj, 1);
7398 }
7399 
7400 /*
7401  * Call on a MOS object that may already have been referenced.
7402  */
7403 static void
7404 mos_obj_refd_multiple(uint64_t obj)
7405 {
7406 	if (obj != 0 && mos_refd_objs != NULL &&
7407 	    !range_tree_contains(mos_refd_objs, obj, 1))
7408 		range_tree_add(mos_refd_objs, obj, 1);
7409 }
7410 
7411 static void
7412 mos_leak_vdev_top_zap(vdev_t *vd)
7413 {
7414 	uint64_t ms_flush_data_obj;
7415 	int error = zap_lookup(spa_meta_objset(vd->vdev_spa),
7416 	    vd->vdev_top_zap, VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS,
7417 	    sizeof (ms_flush_data_obj), 1, &ms_flush_data_obj);
7418 	if (error == ENOENT)
7419 		return;
7420 	ASSERT0(error);
7421 
7422 	mos_obj_refd(ms_flush_data_obj);
7423 }
7424 
7425 static void
7426 mos_leak_vdev(vdev_t *vd)
7427 {
7428 	mos_obj_refd(vd->vdev_dtl_object);
7429 	mos_obj_refd(vd->vdev_ms_array);
7430 	mos_obj_refd(vd->vdev_indirect_config.vic_births_object);
7431 	mos_obj_refd(vd->vdev_indirect_config.vic_mapping_object);
7432 	mos_obj_refd(vd->vdev_leaf_zap);
7433 	if (vd->vdev_checkpoint_sm != NULL)
7434 		mos_obj_refd(vd->vdev_checkpoint_sm->sm_object);
7435 	if (vd->vdev_indirect_mapping != NULL) {
7436 		mos_obj_refd(vd->vdev_indirect_mapping->
7437 		    vim_phys->vimp_counts_object);
7438 	}
7439 	if (vd->vdev_obsolete_sm != NULL)
7440 		mos_obj_refd(vd->vdev_obsolete_sm->sm_object);
7441 
7442 	for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
7443 		metaslab_t *ms = vd->vdev_ms[m];
7444 		mos_obj_refd(space_map_object(ms->ms_sm));
7445 	}
7446 
7447 	if (vd->vdev_top_zap != 0) {
7448 		mos_obj_refd(vd->vdev_top_zap);
7449 		mos_leak_vdev_top_zap(vd);
7450 	}
7451 
7452 	for (uint64_t c = 0; c < vd->vdev_children; c++) {
7453 		mos_leak_vdev(vd->vdev_child[c]);
7454 	}
7455 }
7456 
7457 static void
7458 mos_leak_log_spacemaps(spa_t *spa)
7459 {
7460 	uint64_t spacemap_zap;
7461 	int error = zap_lookup(spa_meta_objset(spa),
7462 	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_LOG_SPACEMAP_ZAP,
7463 	    sizeof (spacemap_zap), 1, &spacemap_zap);
7464 	if (error == ENOENT)
7465 		return;
7466 	ASSERT0(error);
7467 
7468 	mos_obj_refd(spacemap_zap);
7469 	for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
7470 	    sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls))
7471 		mos_obj_refd(sls->sls_sm_obj);
7472 }
7473 
7474 static int
7475 dump_mos_leaks(spa_t *spa)
7476 {
7477 	int rv = 0;
7478 	objset_t *mos = spa->spa_meta_objset;
7479 	dsl_pool_t *dp = spa->spa_dsl_pool;
7480 
7481 	/* Visit and mark all referenced objects in the MOS */
7482 
7483 	mos_obj_refd(DMU_POOL_DIRECTORY_OBJECT);
7484 	mos_obj_refd(spa->spa_pool_props_object);
7485 	mos_obj_refd(spa->spa_config_object);
7486 	mos_obj_refd(spa->spa_ddt_stat_object);
7487 	mos_obj_refd(spa->spa_feat_desc_obj);
7488 	mos_obj_refd(spa->spa_feat_enabled_txg_obj);
7489 	mos_obj_refd(spa->spa_feat_for_read_obj);
7490 	mos_obj_refd(spa->spa_feat_for_write_obj);
7491 	mos_obj_refd(spa->spa_history);
7492 	mos_obj_refd(spa->spa_errlog_last);
7493 	mos_obj_refd(spa->spa_errlog_scrub);
7494 	mos_obj_refd(spa->spa_all_vdev_zaps);
7495 	mos_obj_refd(spa->spa_dsl_pool->dp_bptree_obj);
7496 	mos_obj_refd(spa->spa_dsl_pool->dp_tmp_userrefs_obj);
7497 	mos_obj_refd(spa->spa_dsl_pool->dp_scan->scn_phys.scn_queue_obj);
7498 	bpobj_count_refd(&spa->spa_deferred_bpobj);
7499 	mos_obj_refd(dp->dp_empty_bpobj);
7500 	bpobj_count_refd(&dp->dp_obsolete_bpobj);
7501 	bpobj_count_refd(&dp->dp_free_bpobj);
7502 	mos_obj_refd(spa->spa_l2cache.sav_object);
7503 	mos_obj_refd(spa->spa_spares.sav_object);
7504 
7505 	if (spa->spa_syncing_log_sm != NULL)
7506 		mos_obj_refd(spa->spa_syncing_log_sm->sm_object);
7507 	mos_leak_log_spacemaps(spa);
7508 
7509 	mos_obj_refd(spa->spa_condensing_indirect_phys.
7510 	    scip_next_mapping_object);
7511 	mos_obj_refd(spa->spa_condensing_indirect_phys.
7512 	    scip_prev_obsolete_sm_object);
7513 	if (spa->spa_condensing_indirect_phys.scip_next_mapping_object != 0) {
7514 		vdev_indirect_mapping_t *vim =
7515 		    vdev_indirect_mapping_open(mos,
7516 		    spa->spa_condensing_indirect_phys.scip_next_mapping_object);
7517 		mos_obj_refd(vim->vim_phys->vimp_counts_object);
7518 		vdev_indirect_mapping_close(vim);
7519 	}
7520 	deleted_livelists_dump_mos(spa);
7521 
7522 	if (dp->dp_origin_snap != NULL) {
7523 		dsl_dataset_t *ds;
7524 
7525 		dsl_pool_config_enter(dp, FTAG);
7526 		VERIFY0(dsl_dataset_hold_obj(dp,
7527 		    dsl_dataset_phys(dp->dp_origin_snap)->ds_next_snap_obj,
7528 		    FTAG, &ds));
7529 		count_ds_mos_objects(ds);
7530 		dump_blkptr_list(&ds->ds_deadlist, "Deadlist");
7531 		dsl_dataset_rele(ds, FTAG);
7532 		dsl_pool_config_exit(dp, FTAG);
7533 
7534 		count_ds_mos_objects(dp->dp_origin_snap);
7535 		dump_blkptr_list(&dp->dp_origin_snap->ds_deadlist, "Deadlist");
7536 	}
7537 	count_dir_mos_objects(dp->dp_mos_dir);
7538 	if (dp->dp_free_dir != NULL)
7539 		count_dir_mos_objects(dp->dp_free_dir);
7540 	if (dp->dp_leak_dir != NULL)
7541 		count_dir_mos_objects(dp->dp_leak_dir);
7542 
7543 	mos_leak_vdev(spa->spa_root_vdev);
7544 
7545 	for (uint64_t class = 0; class < DDT_CLASSES; class++) {
7546 		for (uint64_t type = 0; type < DDT_TYPES; type++) {
7547 			for (uint64_t cksum = 0;
7548 			    cksum < ZIO_CHECKSUM_FUNCTIONS; cksum++) {
7549 				ddt_t *ddt = spa->spa_ddt[cksum];
7550 				mos_obj_refd(ddt->ddt_object[type][class]);
7551 			}
7552 		}
7553 	}
7554 
7555 	/*
7556 	 * Visit all allocated objects and make sure they are referenced.
7557 	 */
7558 	uint64_t object = 0;
7559 	while (dmu_object_next(mos, &object, B_FALSE, 0) == 0) {
7560 		if (range_tree_contains(mos_refd_objs, object, 1)) {
7561 			range_tree_remove(mos_refd_objs, object, 1);
7562 		} else {
7563 			dmu_object_info_t doi;
7564 			const char *name;
7565 			dmu_object_info(mos, object, &doi);
7566 			if (doi.doi_type & DMU_OT_NEWTYPE) {
7567 				dmu_object_byteswap_t bswap =
7568 				    DMU_OT_BYTESWAP(doi.doi_type);
7569 				name = dmu_ot_byteswap[bswap].ob_name;
7570 			} else {
7571 				name = dmu_ot[doi.doi_type].ot_name;
7572 			}
7573 
7574 			(void) printf("MOS object %llu (%s) leaked\n",
7575 			    (u_longlong_t)object, name);
7576 			rv = 2;
7577 		}
7578 	}
7579 	(void) range_tree_walk(mos_refd_objs, mos_leaks_cb, NULL);
7580 	if (!range_tree_is_empty(mos_refd_objs))
7581 		rv = 2;
7582 	range_tree_vacate(mos_refd_objs, NULL, NULL);
7583 	range_tree_destroy(mos_refd_objs);
7584 	return (rv);
7585 }
7586 
7587 typedef struct log_sm_obsolete_stats_arg {
7588 	uint64_t lsos_current_txg;
7589 
7590 	uint64_t lsos_total_entries;
7591 	uint64_t lsos_valid_entries;
7592 
7593 	uint64_t lsos_sm_entries;
7594 	uint64_t lsos_valid_sm_entries;
7595 } log_sm_obsolete_stats_arg_t;
7596 
7597 static int
7598 log_spacemap_obsolete_stats_cb(spa_t *spa, space_map_entry_t *sme,
7599     uint64_t txg, void *arg)
7600 {
7601 	log_sm_obsolete_stats_arg_t *lsos = arg;
7602 
7603 	uint64_t offset = sme->sme_offset;
7604 	uint64_t vdev_id = sme->sme_vdev;
7605 
7606 	if (lsos->lsos_current_txg == 0) {
7607 		/* this is the first log */
7608 		lsos->lsos_current_txg = txg;
7609 	} else if (lsos->lsos_current_txg < txg) {
7610 		/* we just changed log - print stats and reset */
7611 		(void) printf("%-8llu valid entries out of %-8llu - txg %llu\n",
7612 		    (u_longlong_t)lsos->lsos_valid_sm_entries,
7613 		    (u_longlong_t)lsos->lsos_sm_entries,
7614 		    (u_longlong_t)lsos->lsos_current_txg);
7615 		lsos->lsos_valid_sm_entries = 0;
7616 		lsos->lsos_sm_entries = 0;
7617 		lsos->lsos_current_txg = txg;
7618 	}
7619 	ASSERT3U(lsos->lsos_current_txg, ==, txg);
7620 
7621 	lsos->lsos_sm_entries++;
7622 	lsos->lsos_total_entries++;
7623 
7624 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
7625 	if (!vdev_is_concrete(vd))
7626 		return (0);
7627 
7628 	metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
7629 	ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
7630 
7631 	if (txg < metaslab_unflushed_txg(ms))
7632 		return (0);
7633 	lsos->lsos_valid_sm_entries++;
7634 	lsos->lsos_valid_entries++;
7635 	return (0);
7636 }
7637 
7638 static void
7639 dump_log_spacemap_obsolete_stats(spa_t *spa)
7640 {
7641 	if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
7642 		return;
7643 
7644 	log_sm_obsolete_stats_arg_t lsos = {0};
7645 
7646 	(void) printf("Log Space Map Obsolete Entry Statistics:\n");
7647 
7648 	iterate_through_spacemap_logs(spa,
7649 	    log_spacemap_obsolete_stats_cb, &lsos);
7650 
7651 	/* print stats for latest log */
7652 	(void) printf("%-8llu valid entries out of %-8llu - txg %llu\n",
7653 	    (u_longlong_t)lsos.lsos_valid_sm_entries,
7654 	    (u_longlong_t)lsos.lsos_sm_entries,
7655 	    (u_longlong_t)lsos.lsos_current_txg);
7656 
7657 	(void) printf("%-8llu valid entries out of %-8llu - total\n\n",
7658 	    (u_longlong_t)lsos.lsos_valid_entries,
7659 	    (u_longlong_t)lsos.lsos_total_entries);
7660 }
7661 
7662 static void
7663 dump_zpool(spa_t *spa)
7664 {
7665 	dsl_pool_t *dp = spa_get_dsl(spa);
7666 	int rc = 0;
7667 
7668 	if (dump_opt['y']) {
7669 		livelist_metaslab_validate(spa);
7670 	}
7671 
7672 	if (dump_opt['S']) {
7673 		dump_simulated_ddt(spa);
7674 		return;
7675 	}
7676 
7677 	if (!dump_opt['e'] && dump_opt['C'] > 1) {
7678 		(void) printf("\nCached configuration:\n");
7679 		dump_nvlist(spa->spa_config, 8);
7680 	}
7681 
7682 	if (dump_opt['C'])
7683 		dump_config(spa);
7684 
7685 	if (dump_opt['u'])
7686 		dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
7687 
7688 	if (dump_opt['D'])
7689 		dump_all_ddts(spa);
7690 
7691 	if (dump_opt['d'] > 2 || dump_opt['m'])
7692 		dump_metaslabs(spa);
7693 	if (dump_opt['M'])
7694 		dump_metaslab_groups(spa, dump_opt['M'] > 1);
7695 	if (dump_opt['d'] > 2 || dump_opt['m']) {
7696 		dump_log_spacemaps(spa);
7697 		dump_log_spacemap_obsolete_stats(spa);
7698 	}
7699 
7700 	if (dump_opt['d'] || dump_opt['i']) {
7701 		spa_feature_t f;
7702 		mos_refd_objs = range_tree_create(NULL, RANGE_SEG64, NULL, 0,
7703 		    0);
7704 		dump_objset(dp->dp_meta_objset);
7705 
7706 		if (dump_opt['d'] >= 3) {
7707 			dsl_pool_t *dp = spa->spa_dsl_pool;
7708 			dump_full_bpobj(&spa->spa_deferred_bpobj,
7709 			    "Deferred frees", 0);
7710 			if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
7711 				dump_full_bpobj(&dp->dp_free_bpobj,
7712 				    "Pool snapshot frees", 0);
7713 			}
7714 			if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
7715 				ASSERT(spa_feature_is_enabled(spa,
7716 				    SPA_FEATURE_DEVICE_REMOVAL));
7717 				dump_full_bpobj(&dp->dp_obsolete_bpobj,
7718 				    "Pool obsolete blocks", 0);
7719 			}
7720 
7721 			if (spa_feature_is_active(spa,
7722 			    SPA_FEATURE_ASYNC_DESTROY)) {
7723 				dump_bptree(spa->spa_meta_objset,
7724 				    dp->dp_bptree_obj,
7725 				    "Pool dataset frees");
7726 			}
7727 			dump_dtl(spa->spa_root_vdev, 0);
7728 		}
7729 
7730 		for (spa_feature_t f = 0; f < SPA_FEATURES; f++)
7731 			global_feature_count[f] = UINT64_MAX;
7732 		global_feature_count[SPA_FEATURE_REDACTION_BOOKMARKS] = 0;
7733 		global_feature_count[SPA_FEATURE_BOOKMARK_WRITTEN] = 0;
7734 		global_feature_count[SPA_FEATURE_LIVELIST] = 0;
7735 
7736 		(void) dmu_objset_find(spa_name(spa), dump_one_objset,
7737 		    NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
7738 
7739 		if (rc == 0 && !dump_opt['L'])
7740 			rc = dump_mos_leaks(spa);
7741 
7742 		for (f = 0; f < SPA_FEATURES; f++) {
7743 			uint64_t refcount;
7744 
7745 			uint64_t *arr;
7746 			if (!(spa_feature_table[f].fi_flags &
7747 			    ZFEATURE_FLAG_PER_DATASET)) {
7748 				if (global_feature_count[f] == UINT64_MAX)
7749 					continue;
7750 				if (!spa_feature_is_enabled(spa, f)) {
7751 					ASSERT0(global_feature_count[f]);
7752 					continue;
7753 				}
7754 				arr = global_feature_count;
7755 			} else {
7756 				if (!spa_feature_is_enabled(spa, f)) {
7757 					ASSERT0(dataset_feature_count[f]);
7758 					continue;
7759 				}
7760 				arr = dataset_feature_count;
7761 			}
7762 			if (feature_get_refcount(spa, &spa_feature_table[f],
7763 			    &refcount) == ENOTSUP)
7764 				continue;
7765 			if (arr[f] != refcount) {
7766 				(void) printf("%s feature refcount mismatch: "
7767 				    "%lld consumers != %lld refcount\n",
7768 				    spa_feature_table[f].fi_uname,
7769 				    (longlong_t)arr[f], (longlong_t)refcount);
7770 				rc = 2;
7771 			} else {
7772 				(void) printf("Verified %s feature refcount "
7773 				    "of %llu is correct\n",
7774 				    spa_feature_table[f].fi_uname,
7775 				    (longlong_t)refcount);
7776 			}
7777 		}
7778 
7779 		if (rc == 0)
7780 			rc = verify_device_removal_feature_counts(spa);
7781 	}
7782 
7783 	if (rc == 0 && (dump_opt['b'] || dump_opt['c']))
7784 		rc = dump_block_stats(spa);
7785 
7786 	if (rc == 0)
7787 		rc = verify_spacemap_refcounts(spa);
7788 
7789 	if (dump_opt['s'])
7790 		show_pool_stats(spa);
7791 
7792 	if (dump_opt['h'])
7793 		dump_history(spa);
7794 
7795 	if (rc == 0)
7796 		rc = verify_checkpoint(spa);
7797 
7798 	if (rc != 0) {
7799 		dump_debug_buffer();
7800 		exit(rc);
7801 	}
7802 }
7803 
7804 #define	ZDB_FLAG_CHECKSUM	0x0001
7805 #define	ZDB_FLAG_DECOMPRESS	0x0002
7806 #define	ZDB_FLAG_BSWAP		0x0004
7807 #define	ZDB_FLAG_GBH		0x0008
7808 #define	ZDB_FLAG_INDIRECT	0x0010
7809 #define	ZDB_FLAG_RAW		0x0020
7810 #define	ZDB_FLAG_PRINT_BLKPTR	0x0040
7811 #define	ZDB_FLAG_VERBOSE	0x0080
7812 
7813 static int flagbits[256];
7814 static char flagbitstr[16];
7815 
7816 static void
7817 zdb_print_blkptr(const blkptr_t *bp, int flags)
7818 {
7819 	char blkbuf[BP_SPRINTF_LEN];
7820 
7821 	if (flags & ZDB_FLAG_BSWAP)
7822 		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
7823 
7824 	snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
7825 	(void) printf("%s\n", blkbuf);
7826 }
7827 
7828 static void
7829 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
7830 {
7831 	int i;
7832 
7833 	for (i = 0; i < nbps; i++)
7834 		zdb_print_blkptr(&bp[i], flags);
7835 }
7836 
7837 static void
7838 zdb_dump_gbh(void *buf, int flags)
7839 {
7840 	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
7841 }
7842 
7843 static void
7844 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
7845 {
7846 	if (flags & ZDB_FLAG_BSWAP)
7847 		byteswap_uint64_array(buf, size);
7848 	VERIFY(write(fileno(stdout), buf, size) == size);
7849 }
7850 
7851 static void
7852 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
7853 {
7854 	uint64_t *d = (uint64_t *)buf;
7855 	unsigned nwords = size / sizeof (uint64_t);
7856 	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
7857 	unsigned i, j;
7858 	const char *hdr;
7859 	char *c;
7860 
7861 
7862 	if (do_bswap)
7863 		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
7864 	else
7865 		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
7866 
7867 	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
7868 
7869 #ifdef _LITTLE_ENDIAN
7870 	/* correct the endianness */
7871 	do_bswap = !do_bswap;
7872 #endif
7873 	for (i = 0; i < nwords; i += 2) {
7874 		(void) printf("%06llx:  %016llx  %016llx  ",
7875 		    (u_longlong_t)(i * sizeof (uint64_t)),
7876 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
7877 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
7878 
7879 		c = (char *)&d[i];
7880 		for (j = 0; j < 2 * sizeof (uint64_t); j++)
7881 			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
7882 		(void) printf("\n");
7883 	}
7884 }
7885 
7886 /*
7887  * There are two acceptable formats:
7888  *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
7889  *	child[.child]*    - For example: 0.1.1
7890  *
7891  * The second form can be used to specify arbitrary vdevs anywhere
7892  * in the hierarchy.  For example, in a pool with a mirror of
7893  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
7894  */
7895 static vdev_t *
7896 zdb_vdev_lookup(vdev_t *vdev, const char *path)
7897 {
7898 	char *s, *p, *q;
7899 	unsigned i;
7900 
7901 	if (vdev == NULL)
7902 		return (NULL);
7903 
7904 	/* First, assume the x.x.x.x format */
7905 	i = strtoul(path, &s, 10);
7906 	if (s == path || (s && *s != '.' && *s != '\0'))
7907 		goto name;
7908 	if (i >= vdev->vdev_children)
7909 		return (NULL);
7910 
7911 	vdev = vdev->vdev_child[i];
7912 	if (s && *s == '\0')
7913 		return (vdev);
7914 	return (zdb_vdev_lookup(vdev, s+1));
7915 
7916 name:
7917 	for (i = 0; i < vdev->vdev_children; i++) {
7918 		vdev_t *vc = vdev->vdev_child[i];
7919 
7920 		if (vc->vdev_path == NULL) {
7921 			vc = zdb_vdev_lookup(vc, path);
7922 			if (vc == NULL)
7923 				continue;
7924 			else
7925 				return (vc);
7926 		}
7927 
7928 		p = strrchr(vc->vdev_path, '/');
7929 		p = p ? p + 1 : vc->vdev_path;
7930 		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
7931 
7932 		if (strcmp(vc->vdev_path, path) == 0)
7933 			return (vc);
7934 		if (strcmp(p, path) == 0)
7935 			return (vc);
7936 		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
7937 			return (vc);
7938 	}
7939 
7940 	return (NULL);
7941 }
7942 
7943 static int
7944 name_from_objset_id(spa_t *spa, uint64_t objset_id, char *outstr)
7945 {
7946 	dsl_dataset_t *ds;
7947 
7948 	dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
7949 	int error = dsl_dataset_hold_obj(spa->spa_dsl_pool, objset_id,
7950 	    NULL, &ds);
7951 	if (error != 0) {
7952 		(void) fprintf(stderr, "failed to hold objset %llu: %s\n",
7953 		    (u_longlong_t)objset_id, strerror(error));
7954 		dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
7955 		return (error);
7956 	}
7957 	dsl_dataset_name(ds, outstr);
7958 	dsl_dataset_rele(ds, NULL);
7959 	dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
7960 	return (0);
7961 }
7962 
7963 static boolean_t
7964 zdb_parse_block_sizes(char *sizes, uint64_t *lsize, uint64_t *psize)
7965 {
7966 	char *s0, *s1, *tmp = NULL;
7967 
7968 	if (sizes == NULL)
7969 		return (B_FALSE);
7970 
7971 	s0 = strtok_r(sizes, "/", &tmp);
7972 	if (s0 == NULL)
7973 		return (B_FALSE);
7974 	s1 = strtok_r(NULL, "/", &tmp);
7975 	*lsize = strtoull(s0, NULL, 16);
7976 	*psize = s1 ? strtoull(s1, NULL, 16) : *lsize;
7977 	return (*lsize >= *psize && *psize > 0);
7978 }
7979 
7980 #define	ZIO_COMPRESS_MASK(alg)	(1ULL << (ZIO_COMPRESS_##alg))
7981 
7982 static boolean_t
7983 zdb_decompress_block(abd_t *pabd, void *buf, void *lbuf, uint64_t lsize,
7984     uint64_t psize, int flags)
7985 {
7986 	(void) buf;
7987 	boolean_t exceeded = B_FALSE;
7988 	/*
7989 	 * We don't know how the data was compressed, so just try
7990 	 * every decompress function at every inflated blocksize.
7991 	 */
7992 	void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
7993 	int cfuncs[ZIO_COMPRESS_FUNCTIONS] = { 0 };
7994 	int *cfuncp = cfuncs;
7995 	uint64_t maxlsize = SPA_MAXBLOCKSIZE;
7996 	uint64_t mask = ZIO_COMPRESS_MASK(ON) | ZIO_COMPRESS_MASK(OFF) |
7997 	    ZIO_COMPRESS_MASK(INHERIT) | ZIO_COMPRESS_MASK(EMPTY) |
7998 	    (getenv("ZDB_NO_ZLE") ? ZIO_COMPRESS_MASK(ZLE) : 0);
7999 	*cfuncp++ = ZIO_COMPRESS_LZ4;
8000 	*cfuncp++ = ZIO_COMPRESS_LZJB;
8001 	mask |= ZIO_COMPRESS_MASK(LZ4) | ZIO_COMPRESS_MASK(LZJB);
8002 	for (int c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++)
8003 		if (((1ULL << c) & mask) == 0)
8004 			*cfuncp++ = c;
8005 
8006 	/*
8007 	 * On the one hand, with SPA_MAXBLOCKSIZE at 16MB, this
8008 	 * could take a while and we should let the user know
8009 	 * we are not stuck.  On the other hand, printing progress
8010 	 * info gets old after a while.  User can specify 'v' flag
8011 	 * to see the progression.
8012 	 */
8013 	if (lsize == psize)
8014 		lsize += SPA_MINBLOCKSIZE;
8015 	else
8016 		maxlsize = lsize;
8017 	for (; lsize <= maxlsize; lsize += SPA_MINBLOCKSIZE) {
8018 		for (cfuncp = cfuncs; *cfuncp; cfuncp++) {
8019 			if (flags & ZDB_FLAG_VERBOSE) {
8020 				(void) fprintf(stderr,
8021 				    "Trying %05llx -> %05llx (%s)\n",
8022 				    (u_longlong_t)psize,
8023 				    (u_longlong_t)lsize,
8024 				    zio_compress_table[*cfuncp].\
8025 				    ci_name);
8026 			}
8027 
8028 			/*
8029 			 * We randomize lbuf2, and decompress to both
8030 			 * lbuf and lbuf2. This way, we will know if
8031 			 * decompression fill exactly to lsize.
8032 			 */
8033 			VERIFY0(random_get_pseudo_bytes(lbuf2, lsize));
8034 
8035 			if (zio_decompress_data(*cfuncp, pabd,
8036 			    lbuf, psize, lsize, NULL) == 0 &&
8037 			    zio_decompress_data(*cfuncp, pabd,
8038 			    lbuf2, psize, lsize, NULL) == 0 &&
8039 			    memcmp(lbuf, lbuf2, lsize) == 0)
8040 				break;
8041 		}
8042 		if (*cfuncp != 0)
8043 			break;
8044 	}
8045 	umem_free(lbuf2, SPA_MAXBLOCKSIZE);
8046 
8047 	if (lsize > maxlsize) {
8048 		exceeded = B_TRUE;
8049 	}
8050 	if (*cfuncp == ZIO_COMPRESS_ZLE) {
8051 		printf("\nZLE decompression was selected. If you "
8052 		    "suspect the results are wrong,\ntry avoiding ZLE "
8053 		    "by setting and exporting ZDB_NO_ZLE=\"true\"\n");
8054 	}
8055 
8056 	return (exceeded);
8057 }
8058 
8059 /*
8060  * Read a block from a pool and print it out.  The syntax of the
8061  * block descriptor is:
8062  *
8063  *	pool:vdev_specifier:offset:[lsize/]psize[:flags]
8064  *
8065  *	pool           - The name of the pool you wish to read from
8066  *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
8067  *	offset         - offset, in hex, in bytes
8068  *	size           - Amount of data to read, in hex, in bytes
8069  *	flags          - A string of characters specifying options
8070  *		 b: Decode a blkptr at given offset within block
8071  *		 c: Calculate and display checksums
8072  *		 d: Decompress data before dumping
8073  *		 e: Byteswap data before dumping
8074  *		 g: Display data as a gang block header
8075  *		 i: Display as an indirect block
8076  *		 r: Dump raw data to stdout
8077  *		 v: Verbose
8078  *
8079  */
8080 static void
8081 zdb_read_block(char *thing, spa_t *spa)
8082 {
8083 	blkptr_t blk, *bp = &blk;
8084 	dva_t *dva = bp->blk_dva;
8085 	int flags = 0;
8086 	uint64_t offset = 0, psize = 0, lsize = 0, blkptr_offset = 0;
8087 	zio_t *zio;
8088 	vdev_t *vd;
8089 	abd_t *pabd;
8090 	void *lbuf, *buf;
8091 	char *s, *p, *dup, *vdev, *flagstr, *sizes, *tmp = NULL;
8092 	int i, error;
8093 	boolean_t borrowed = B_FALSE, found = B_FALSE;
8094 
8095 	dup = strdup(thing);
8096 	s = strtok_r(dup, ":", &tmp);
8097 	vdev = s ? s : "";
8098 	s = strtok_r(NULL, ":", &tmp);
8099 	offset = strtoull(s ? s : "", NULL, 16);
8100 	sizes = strtok_r(NULL, ":", &tmp);
8101 	s = strtok_r(NULL, ":", &tmp);
8102 	flagstr = strdup(s ? s : "");
8103 
8104 	s = NULL;
8105 	tmp = NULL;
8106 	if (!zdb_parse_block_sizes(sizes, &lsize, &psize))
8107 		s = "invalid size(s)";
8108 	if (!IS_P2ALIGNED(psize, DEV_BSIZE) || !IS_P2ALIGNED(lsize, DEV_BSIZE))
8109 		s = "size must be a multiple of sector size";
8110 	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
8111 		s = "offset must be a multiple of sector size";
8112 	if (s) {
8113 		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
8114 		goto done;
8115 	}
8116 
8117 	for (s = strtok_r(flagstr, ":", &tmp);
8118 	    s != NULL;
8119 	    s = strtok_r(NULL, ":", &tmp)) {
8120 		for (i = 0; i < strlen(flagstr); i++) {
8121 			int bit = flagbits[(uchar_t)flagstr[i]];
8122 
8123 			if (bit == 0) {
8124 				(void) printf("***Ignoring flag: %c\n",
8125 				    (uchar_t)flagstr[i]);
8126 				continue;
8127 			}
8128 			found = B_TRUE;
8129 			flags |= bit;
8130 
8131 			p = &flagstr[i + 1];
8132 			if (*p != ':' && *p != '\0') {
8133 				int j = 0, nextbit = flagbits[(uchar_t)*p];
8134 				char *end, offstr[8] = { 0 };
8135 				if ((bit == ZDB_FLAG_PRINT_BLKPTR) &&
8136 				    (nextbit == 0)) {
8137 					/* look ahead to isolate the offset */
8138 					while (nextbit == 0 &&
8139 					    strchr(flagbitstr, *p) == NULL) {
8140 						offstr[j] = *p;
8141 						j++;
8142 						if (i + j > strlen(flagstr))
8143 							break;
8144 						p++;
8145 						nextbit = flagbits[(uchar_t)*p];
8146 					}
8147 					blkptr_offset = strtoull(offstr, &end,
8148 					    16);
8149 					i += j;
8150 				} else if (nextbit == 0) {
8151 					(void) printf("***Ignoring flag arg:"
8152 					    " '%c'\n", (uchar_t)*p);
8153 				}
8154 			}
8155 		}
8156 	}
8157 	if (blkptr_offset % sizeof (blkptr_t)) {
8158 		printf("Block pointer offset 0x%llx "
8159 		    "must be divisible by 0x%x\n",
8160 		    (longlong_t)blkptr_offset, (int)sizeof (blkptr_t));
8161 		goto done;
8162 	}
8163 	if (found == B_FALSE && strlen(flagstr) > 0) {
8164 		printf("Invalid flag arg: '%s'\n", flagstr);
8165 		goto done;
8166 	}
8167 
8168 	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
8169 	if (vd == NULL) {
8170 		(void) printf("***Invalid vdev: %s\n", vdev);
8171 		free(dup);
8172 		return;
8173 	} else {
8174 		if (vd->vdev_path)
8175 			(void) fprintf(stderr, "Found vdev: %s\n",
8176 			    vd->vdev_path);
8177 		else
8178 			(void) fprintf(stderr, "Found vdev type: %s\n",
8179 			    vd->vdev_ops->vdev_op_type);
8180 	}
8181 
8182 	pabd = abd_alloc_for_io(SPA_MAXBLOCKSIZE, B_FALSE);
8183 	lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
8184 
8185 	BP_ZERO(bp);
8186 
8187 	DVA_SET_VDEV(&dva[0], vd->vdev_id);
8188 	DVA_SET_OFFSET(&dva[0], offset);
8189 	DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
8190 	DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
8191 
8192 	BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
8193 
8194 	BP_SET_LSIZE(bp, lsize);
8195 	BP_SET_PSIZE(bp, psize);
8196 	BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
8197 	BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
8198 	BP_SET_TYPE(bp, DMU_OT_NONE);
8199 	BP_SET_LEVEL(bp, 0);
8200 	BP_SET_DEDUP(bp, 0);
8201 	BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
8202 
8203 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8204 	zio = zio_root(spa, NULL, NULL, 0);
8205 
8206 	if (vd == vd->vdev_top) {
8207 		/*
8208 		 * Treat this as a normal block read.
8209 		 */
8210 		zio_nowait(zio_read(zio, spa, bp, pabd, psize, NULL, NULL,
8211 		    ZIO_PRIORITY_SYNC_READ,
8212 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
8213 	} else {
8214 		/*
8215 		 * Treat this as a vdev child I/O.
8216 		 */
8217 		zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pabd,
8218 		    psize, ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
8219 		    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_PROPAGATE |
8220 		    ZIO_FLAG_DONT_RETRY | ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW |
8221 		    ZIO_FLAG_OPTIONAL, NULL, NULL));
8222 	}
8223 
8224 	error = zio_wait(zio);
8225 	spa_config_exit(spa, SCL_STATE, FTAG);
8226 
8227 	if (error) {
8228 		(void) printf("Read of %s failed, error: %d\n", thing, error);
8229 		goto out;
8230 	}
8231 
8232 	uint64_t orig_lsize = lsize;
8233 	buf = lbuf;
8234 	if (flags & ZDB_FLAG_DECOMPRESS) {
8235 		boolean_t failed = zdb_decompress_block(pabd, buf, lbuf,
8236 		    lsize, psize, flags);
8237 		if (failed) {
8238 			(void) printf("Decompress of %s failed\n", thing);
8239 			goto out;
8240 		}
8241 	} else {
8242 		buf = abd_borrow_buf_copy(pabd, lsize);
8243 		borrowed = B_TRUE;
8244 	}
8245 	/*
8246 	 * Try to detect invalid block pointer.  If invalid, try
8247 	 * decompressing.
8248 	 */
8249 	if ((flags & ZDB_FLAG_PRINT_BLKPTR || flags & ZDB_FLAG_INDIRECT) &&
8250 	    !(flags & ZDB_FLAG_DECOMPRESS)) {
8251 		const blkptr_t *b = (const blkptr_t *)(void *)
8252 		    ((uintptr_t)buf + (uintptr_t)blkptr_offset);
8253 		if (zfs_blkptr_verify(spa, b, B_FALSE, BLK_VERIFY_ONLY) ==
8254 		    B_FALSE) {
8255 			abd_return_buf_copy(pabd, buf, lsize);
8256 			borrowed = B_FALSE;
8257 			buf = lbuf;
8258 			boolean_t failed = zdb_decompress_block(pabd, buf,
8259 			    lbuf, lsize, psize, flags);
8260 			b = (const blkptr_t *)(void *)
8261 			    ((uintptr_t)buf + (uintptr_t)blkptr_offset);
8262 			if (failed || zfs_blkptr_verify(spa, b, B_FALSE,
8263 			    BLK_VERIFY_LOG) == B_FALSE) {
8264 				printf("invalid block pointer at this DVA\n");
8265 				goto out;
8266 			}
8267 		}
8268 	}
8269 
8270 	if (flags & ZDB_FLAG_PRINT_BLKPTR)
8271 		zdb_print_blkptr((blkptr_t *)(void *)
8272 		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
8273 	else if (flags & ZDB_FLAG_RAW)
8274 		zdb_dump_block_raw(buf, lsize, flags);
8275 	else if (flags & ZDB_FLAG_INDIRECT)
8276 		zdb_dump_indirect((blkptr_t *)buf,
8277 		    orig_lsize / sizeof (blkptr_t), flags);
8278 	else if (flags & ZDB_FLAG_GBH)
8279 		zdb_dump_gbh(buf, flags);
8280 	else
8281 		zdb_dump_block(thing, buf, lsize, flags);
8282 
8283 	/*
8284 	 * If :c was specified, iterate through the checksum table to
8285 	 * calculate and display each checksum for our specified
8286 	 * DVA and length.
8287 	 */
8288 	if ((flags & ZDB_FLAG_CHECKSUM) && !(flags & ZDB_FLAG_RAW) &&
8289 	    !(flags & ZDB_FLAG_GBH)) {
8290 		zio_t *czio;
8291 		(void) printf("\n");
8292 		for (enum zio_checksum ck = ZIO_CHECKSUM_LABEL;
8293 		    ck < ZIO_CHECKSUM_FUNCTIONS; ck++) {
8294 
8295 			if ((zio_checksum_table[ck].ci_flags &
8296 			    ZCHECKSUM_FLAG_EMBEDDED) ||
8297 			    ck == ZIO_CHECKSUM_NOPARITY) {
8298 				continue;
8299 			}
8300 			BP_SET_CHECKSUM(bp, ck);
8301 			spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8302 			czio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
8303 			czio->io_bp = bp;
8304 
8305 			if (vd == vd->vdev_top) {
8306 				zio_nowait(zio_read(czio, spa, bp, pabd, psize,
8307 				    NULL, NULL,
8308 				    ZIO_PRIORITY_SYNC_READ,
8309 				    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW |
8310 				    ZIO_FLAG_DONT_RETRY, NULL));
8311 			} else {
8312 				zio_nowait(zio_vdev_child_io(czio, bp, vd,
8313 				    offset, pabd, psize, ZIO_TYPE_READ,
8314 				    ZIO_PRIORITY_SYNC_READ,
8315 				    ZIO_FLAG_DONT_CACHE |
8316 				    ZIO_FLAG_DONT_PROPAGATE |
8317 				    ZIO_FLAG_DONT_RETRY |
8318 				    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW |
8319 				    ZIO_FLAG_SPECULATIVE |
8320 				    ZIO_FLAG_OPTIONAL, NULL, NULL));
8321 			}
8322 			error = zio_wait(czio);
8323 			if (error == 0 || error == ECKSUM) {
8324 				zio_t *ck_zio = zio_root(spa, NULL, NULL, 0);
8325 				ck_zio->io_offset =
8326 				    DVA_GET_OFFSET(&bp->blk_dva[0]);
8327 				ck_zio->io_bp = bp;
8328 				zio_checksum_compute(ck_zio, ck, pabd, lsize);
8329 				printf("%12s\tcksum=%llx:%llx:%llx:%llx\n",
8330 				    zio_checksum_table[ck].ci_name,
8331 				    (u_longlong_t)bp->blk_cksum.zc_word[0],
8332 				    (u_longlong_t)bp->blk_cksum.zc_word[1],
8333 				    (u_longlong_t)bp->blk_cksum.zc_word[2],
8334 				    (u_longlong_t)bp->blk_cksum.zc_word[3]);
8335 				zio_wait(ck_zio);
8336 			} else {
8337 				printf("error %d reading block\n", error);
8338 			}
8339 			spa_config_exit(spa, SCL_STATE, FTAG);
8340 		}
8341 	}
8342 
8343 	if (borrowed)
8344 		abd_return_buf_copy(pabd, buf, lsize);
8345 
8346 out:
8347 	abd_free(pabd);
8348 	umem_free(lbuf, SPA_MAXBLOCKSIZE);
8349 done:
8350 	free(flagstr);
8351 	free(dup);
8352 }
8353 
8354 static void
8355 zdb_embedded_block(char *thing)
8356 {
8357 	blkptr_t bp = {{{{0}}}};
8358 	unsigned long long *words = (void *)&bp;
8359 	char *buf;
8360 	int err;
8361 
8362 	err = sscanf(thing, "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx:"
8363 	    "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx",
8364 	    words + 0, words + 1, words + 2, words + 3,
8365 	    words + 4, words + 5, words + 6, words + 7,
8366 	    words + 8, words + 9, words + 10, words + 11,
8367 	    words + 12, words + 13, words + 14, words + 15);
8368 	if (err != 16) {
8369 		(void) fprintf(stderr, "invalid input format\n");
8370 		exit(1);
8371 	}
8372 	ASSERT3U(BPE_GET_LSIZE(&bp), <=, SPA_MAXBLOCKSIZE);
8373 	buf = malloc(SPA_MAXBLOCKSIZE);
8374 	if (buf == NULL) {
8375 		(void) fprintf(stderr, "out of memory\n");
8376 		exit(1);
8377 	}
8378 	err = decode_embedded_bp(&bp, buf, BPE_GET_LSIZE(&bp));
8379 	if (err != 0) {
8380 		(void) fprintf(stderr, "decode failed: %u\n", err);
8381 		exit(1);
8382 	}
8383 	zdb_dump_block_raw(buf, BPE_GET_LSIZE(&bp), 0);
8384 	free(buf);
8385 }
8386 
8387 /* check for valid hex or decimal numeric string */
8388 static boolean_t
8389 zdb_numeric(char *str)
8390 {
8391 	int i = 0;
8392 
8393 	if (strlen(str) == 0)
8394 		return (B_FALSE);
8395 	if (strncmp(str, "0x", 2) == 0 || strncmp(str, "0X", 2) == 0)
8396 		i = 2;
8397 	for (; i < strlen(str); i++) {
8398 		if (!isxdigit(str[i]))
8399 			return (B_FALSE);
8400 	}
8401 	return (B_TRUE);
8402 }
8403 
8404 int
8405 main(int argc, char **argv)
8406 {
8407 	int c;
8408 	struct rlimit rl = { 1024, 1024 };
8409 	spa_t *spa = NULL;
8410 	objset_t *os = NULL;
8411 	int dump_all = 1;
8412 	int verbose = 0;
8413 	int error = 0;
8414 	char **searchdirs = NULL;
8415 	int nsearch = 0;
8416 	char *target, *target_pool, dsname[ZFS_MAX_DATASET_NAME_LEN];
8417 	nvlist_t *policy = NULL;
8418 	uint64_t max_txg = UINT64_MAX;
8419 	int64_t objset_id = -1;
8420 	uint64_t object;
8421 	int flags = ZFS_IMPORT_MISSING_LOG;
8422 	int rewind = ZPOOL_NEVER_REWIND;
8423 	char *spa_config_path_env, *objset_str;
8424 	boolean_t target_is_spa = B_TRUE, dataset_lookup = B_FALSE;
8425 	nvlist_t *cfg = NULL;
8426 
8427 	(void) setrlimit(RLIMIT_NOFILE, &rl);
8428 	(void) enable_extended_FILE_stdio(-1, -1);
8429 
8430 	dprintf_setup(&argc, argv);
8431 
8432 	/*
8433 	 * If there is an environment variable SPA_CONFIG_PATH it overrides
8434 	 * default spa_config_path setting. If -U flag is specified it will
8435 	 * override this environment variable settings once again.
8436 	 */
8437 	spa_config_path_env = getenv("SPA_CONFIG_PATH");
8438 	if (spa_config_path_env != NULL)
8439 		spa_config_path = spa_config_path_env;
8440 
8441 	/*
8442 	 * For performance reasons, we set this tunable down. We do so before
8443 	 * the arg parsing section so that the user can override this value if
8444 	 * they choose.
8445 	 */
8446 	zfs_btree_verify_intensity = 3;
8447 
8448 	struct option long_options[] = {
8449 		{"ignore-assertions",	no_argument,		NULL, 'A'},
8450 		{"block-stats",		no_argument,		NULL, 'b'},
8451 		{"checksum",		no_argument,		NULL, 'c'},
8452 		{"config",		no_argument,		NULL, 'C'},
8453 		{"datasets",		no_argument,		NULL, 'd'},
8454 		{"dedup-stats",		no_argument,		NULL, 'D'},
8455 		{"exported",		no_argument,		NULL, 'e'},
8456 		{"embedded-block-pointer",	no_argument,	NULL, 'E'},
8457 		{"automatic-rewind",	no_argument,		NULL, 'F'},
8458 		{"dump-debug-msg",	no_argument,		NULL, 'G'},
8459 		{"history",		no_argument,		NULL, 'h'},
8460 		{"intent-logs",		no_argument,		NULL, 'i'},
8461 		{"inflight",		required_argument,	NULL, 'I'},
8462 		{"checkpointed-state",	no_argument,		NULL, 'k'},
8463 		{"label",		no_argument,		NULL, 'l'},
8464 		{"disable-leak-tracking",	no_argument,	NULL, 'L'},
8465 		{"metaslabs",		no_argument,		NULL, 'm'},
8466 		{"metaslab-groups",	no_argument,		NULL, 'M'},
8467 		{"numeric",		no_argument,		NULL, 'N'},
8468 		{"option",		required_argument,	NULL, 'o'},
8469 		{"object-lookups",	no_argument,		NULL, 'O'},
8470 		{"path",		required_argument,	NULL, 'p'},
8471 		{"parseable",		no_argument,		NULL, 'P'},
8472 		{"skip-label",		no_argument,		NULL, 'q'},
8473 		{"copy-object",		no_argument,		NULL, 'r'},
8474 		{"read-block",		no_argument,		NULL, 'R'},
8475 		{"io-stats",		no_argument,		NULL, 's'},
8476 		{"simulate-dedup",	no_argument,		NULL, 'S'},
8477 		{"txg",			required_argument,	NULL, 't'},
8478 		{"uberblock",		no_argument,		NULL, 'u'},
8479 		{"cachefile",		required_argument,	NULL, 'U'},
8480 		{"verbose",		no_argument,		NULL, 'v'},
8481 		{"verbatim",		no_argument,		NULL, 'V'},
8482 		{"dump-blocks",		required_argument,	NULL, 'x'},
8483 		{"extreme-rewind",	no_argument,		NULL, 'X'},
8484 		{"all-reconstruction",	no_argument,		NULL, 'Y'},
8485 		{"livelist",		no_argument,		NULL, 'y'},
8486 		{"zstd-headers",	no_argument,		NULL, 'Z'},
8487 		{0, 0, 0, 0}
8488 	};
8489 
8490 	while ((c = getopt_long(argc, argv,
8491 	    "AbcCdDeEFGhiI:klLmMNo:Op:PqrRsSt:uU:vVx:XYyZ",
8492 	    long_options, NULL)) != -1) {
8493 		switch (c) {
8494 		case 'b':
8495 		case 'c':
8496 		case 'C':
8497 		case 'd':
8498 		case 'D':
8499 		case 'E':
8500 		case 'G':
8501 		case 'h':
8502 		case 'i':
8503 		case 'l':
8504 		case 'm':
8505 		case 'M':
8506 		case 'N':
8507 		case 'O':
8508 		case 'r':
8509 		case 'R':
8510 		case 's':
8511 		case 'S':
8512 		case 'u':
8513 		case 'y':
8514 		case 'Z':
8515 			dump_opt[c]++;
8516 			dump_all = 0;
8517 			break;
8518 		case 'A':
8519 		case 'e':
8520 		case 'F':
8521 		case 'k':
8522 		case 'L':
8523 		case 'P':
8524 		case 'q':
8525 		case 'X':
8526 			dump_opt[c]++;
8527 			break;
8528 		case 'Y':
8529 			zfs_reconstruct_indirect_combinations_max = INT_MAX;
8530 			zfs_deadman_enabled = 0;
8531 			break;
8532 		/* NB: Sort single match options below. */
8533 		case 'I':
8534 			max_inflight_bytes = strtoull(optarg, NULL, 0);
8535 			if (max_inflight_bytes == 0) {
8536 				(void) fprintf(stderr, "maximum number "
8537 				    "of inflight bytes must be greater "
8538 				    "than 0\n");
8539 				usage();
8540 			}
8541 			break;
8542 		case 'o':
8543 			error = set_global_var(optarg);
8544 			if (error != 0)
8545 				usage();
8546 			break;
8547 		case 'p':
8548 			if (searchdirs == NULL) {
8549 				searchdirs = umem_alloc(sizeof (char *),
8550 				    UMEM_NOFAIL);
8551 			} else {
8552 				char **tmp = umem_alloc((nsearch + 1) *
8553 				    sizeof (char *), UMEM_NOFAIL);
8554 				memcpy(tmp, searchdirs, nsearch *
8555 				    sizeof (char *));
8556 				umem_free(searchdirs,
8557 				    nsearch * sizeof (char *));
8558 				searchdirs = tmp;
8559 			}
8560 			searchdirs[nsearch++] = optarg;
8561 			break;
8562 		case 't':
8563 			max_txg = strtoull(optarg, NULL, 0);
8564 			if (max_txg < TXG_INITIAL) {
8565 				(void) fprintf(stderr, "incorrect txg "
8566 				    "specified: %s\n", optarg);
8567 				usage();
8568 			}
8569 			break;
8570 		case 'U':
8571 			spa_config_path = optarg;
8572 			if (spa_config_path[0] != '/') {
8573 				(void) fprintf(stderr,
8574 				    "cachefile must be an absolute path "
8575 				    "(i.e. start with a slash)\n");
8576 				usage();
8577 			}
8578 			break;
8579 		case 'v':
8580 			verbose++;
8581 			break;
8582 		case 'V':
8583 			flags = ZFS_IMPORT_VERBATIM;
8584 			break;
8585 		case 'x':
8586 			vn_dumpdir = optarg;
8587 			break;
8588 		default:
8589 			usage();
8590 			break;
8591 		}
8592 	}
8593 
8594 	if (!dump_opt['e'] && searchdirs != NULL) {
8595 		(void) fprintf(stderr, "-p option requires use of -e\n");
8596 		usage();
8597 	}
8598 #if defined(_LP64)
8599 	/*
8600 	 * ZDB does not typically re-read blocks; therefore limit the ARC
8601 	 * to 256 MB, which can be used entirely for metadata.
8602 	 */
8603 	zfs_arc_min = zfs_arc_meta_min = 2ULL << SPA_MAXBLOCKSHIFT;
8604 	zfs_arc_max = zfs_arc_meta_limit = 256 * 1024 * 1024;
8605 #endif
8606 
8607 	/*
8608 	 * "zdb -c" uses checksum-verifying scrub i/os which are async reads.
8609 	 * "zdb -b" uses traversal prefetch which uses async reads.
8610 	 * For good performance, let several of them be active at once.
8611 	 */
8612 	zfs_vdev_async_read_max_active = 10;
8613 
8614 	/*
8615 	 * Disable reference tracking for better performance.
8616 	 */
8617 	reference_tracking_enable = B_FALSE;
8618 
8619 	/*
8620 	 * Do not fail spa_load when spa_load_verify fails. This is needed
8621 	 * to load non-idle pools.
8622 	 */
8623 	spa_load_verify_dryrun = B_TRUE;
8624 
8625 	/*
8626 	 * ZDB should have ability to read spacemaps.
8627 	 */
8628 	spa_mode_readable_spacemaps = B_TRUE;
8629 
8630 	kernel_init(SPA_MODE_READ);
8631 
8632 	if (dump_all)
8633 		verbose = MAX(verbose, 1);
8634 
8635 	for (c = 0; c < 256; c++) {
8636 		if (dump_all && strchr("AeEFklLNOPrRSXy", c) == NULL)
8637 			dump_opt[c] = 1;
8638 		if (dump_opt[c])
8639 			dump_opt[c] += verbose;
8640 	}
8641 
8642 	libspl_set_assert_ok((dump_opt['A'] == 1) || (dump_opt['A'] > 2));
8643 	zfs_recover = (dump_opt['A'] > 1);
8644 
8645 	argc -= optind;
8646 	argv += optind;
8647 	if (argc < 2 && dump_opt['R'])
8648 		usage();
8649 
8650 	if (dump_opt['E']) {
8651 		if (argc != 1)
8652 			usage();
8653 		zdb_embedded_block(argv[0]);
8654 		return (0);
8655 	}
8656 
8657 	if (argc < 1) {
8658 		if (!dump_opt['e'] && dump_opt['C']) {
8659 			dump_cachefile(spa_config_path);
8660 			return (0);
8661 		}
8662 		usage();
8663 	}
8664 
8665 	if (dump_opt['l'])
8666 		return (dump_label(argv[0]));
8667 
8668 	if (dump_opt['O']) {
8669 		if (argc != 2)
8670 			usage();
8671 		dump_opt['v'] = verbose + 3;
8672 		return (dump_path(argv[0], argv[1], NULL));
8673 	}
8674 	if (dump_opt['r']) {
8675 		target_is_spa = B_FALSE;
8676 		if (argc != 3)
8677 			usage();
8678 		dump_opt['v'] = verbose;
8679 		error = dump_path(argv[0], argv[1], &object);
8680 	}
8681 
8682 	if (dump_opt['X'] || dump_opt['F'])
8683 		rewind = ZPOOL_DO_REWIND |
8684 		    (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
8685 
8686 	/* -N implies -d */
8687 	if (dump_opt['N'] && dump_opt['d'] == 0)
8688 		dump_opt['d'] = dump_opt['N'];
8689 
8690 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
8691 	    nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, max_txg) != 0 ||
8692 	    nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY, rewind) != 0)
8693 		fatal("internal error: %s", strerror(ENOMEM));
8694 
8695 	error = 0;
8696 	target = argv[0];
8697 
8698 	if (strpbrk(target, "/@") != NULL) {
8699 		size_t targetlen;
8700 
8701 		target_pool = strdup(target);
8702 		*strpbrk(target_pool, "/@") = '\0';
8703 
8704 		target_is_spa = B_FALSE;
8705 		targetlen = strlen(target);
8706 		if (targetlen && target[targetlen - 1] == '/')
8707 			target[targetlen - 1] = '\0';
8708 
8709 		/*
8710 		 * See if an objset ID was supplied (-d <pool>/<objset ID>).
8711 		 * To disambiguate tank/100, consider the 100 as objsetID
8712 		 * if -N was given, otherwise 100 is an objsetID iff
8713 		 * tank/100 as a named dataset fails on lookup.
8714 		 */
8715 		objset_str = strchr(target, '/');
8716 		if (objset_str && strlen(objset_str) > 1 &&
8717 		    zdb_numeric(objset_str + 1)) {
8718 			char *endptr;
8719 			errno = 0;
8720 			objset_str++;
8721 			objset_id = strtoull(objset_str, &endptr, 0);
8722 			/* dataset 0 is the same as opening the pool */
8723 			if (errno == 0 && endptr != objset_str &&
8724 			    objset_id != 0) {
8725 				if (dump_opt['N'])
8726 					dataset_lookup = B_TRUE;
8727 			}
8728 			/* normal dataset name not an objset ID */
8729 			if (endptr == objset_str) {
8730 				objset_id = -1;
8731 			}
8732 		} else if (objset_str && !zdb_numeric(objset_str + 1) &&
8733 		    dump_opt['N']) {
8734 			printf("Supply a numeric objset ID with -N\n");
8735 			exit(1);
8736 		}
8737 	} else {
8738 		target_pool = target;
8739 	}
8740 
8741 	if (dump_opt['e']) {
8742 		importargs_t args = { 0 };
8743 
8744 		args.paths = nsearch;
8745 		args.path = searchdirs;
8746 		args.can_be_active = B_TRUE;
8747 
8748 		error = zpool_find_config(NULL, target_pool, &cfg, &args,
8749 		    &libzpool_config_ops);
8750 
8751 		if (error == 0) {
8752 
8753 			if (nvlist_add_nvlist(cfg,
8754 			    ZPOOL_LOAD_POLICY, policy) != 0) {
8755 				fatal("can't open '%s': %s",
8756 				    target, strerror(ENOMEM));
8757 			}
8758 
8759 			if (dump_opt['C'] > 1) {
8760 				(void) printf("\nConfiguration for import:\n");
8761 				dump_nvlist(cfg, 8);
8762 			}
8763 
8764 			/*
8765 			 * Disable the activity check to allow examination of
8766 			 * active pools.
8767 			 */
8768 			error = spa_import(target_pool, cfg, NULL,
8769 			    flags | ZFS_IMPORT_SKIP_MMP);
8770 		}
8771 	}
8772 
8773 	if (searchdirs != NULL) {
8774 		umem_free(searchdirs, nsearch * sizeof (char *));
8775 		searchdirs = NULL;
8776 	}
8777 
8778 	/*
8779 	 * import_checkpointed_state makes the assumption that the
8780 	 * target pool that we pass it is already part of the spa
8781 	 * namespace. Because of that we need to make sure to call
8782 	 * it always after the -e option has been processed, which
8783 	 * imports the pool to the namespace if it's not in the
8784 	 * cachefile.
8785 	 */
8786 	char *checkpoint_pool = NULL;
8787 	char *checkpoint_target = NULL;
8788 	if (dump_opt['k']) {
8789 		checkpoint_pool = import_checkpointed_state(target, cfg,
8790 		    &checkpoint_target);
8791 
8792 		if (checkpoint_target != NULL)
8793 			target = checkpoint_target;
8794 	}
8795 
8796 	if (cfg != NULL) {
8797 		nvlist_free(cfg);
8798 		cfg = NULL;
8799 	}
8800 
8801 	if (target_pool != target)
8802 		free(target_pool);
8803 
8804 	if (error == 0) {
8805 		if (dump_opt['k'] && (target_is_spa || dump_opt['R'])) {
8806 			ASSERT(checkpoint_pool != NULL);
8807 			ASSERT(checkpoint_target == NULL);
8808 
8809 			error = spa_open(checkpoint_pool, &spa, FTAG);
8810 			if (error != 0) {
8811 				fatal("Tried to open pool \"%s\" but "
8812 				    "spa_open() failed with error %d\n",
8813 				    checkpoint_pool, error);
8814 			}
8815 
8816 		} else if (target_is_spa || dump_opt['R'] || objset_id == 0) {
8817 			zdb_set_skip_mmp(target);
8818 			error = spa_open_rewind(target, &spa, FTAG, policy,
8819 			    NULL);
8820 			if (error) {
8821 				/*
8822 				 * If we're missing the log device then
8823 				 * try opening the pool after clearing the
8824 				 * log state.
8825 				 */
8826 				mutex_enter(&spa_namespace_lock);
8827 				if ((spa = spa_lookup(target)) != NULL &&
8828 				    spa->spa_log_state == SPA_LOG_MISSING) {
8829 					spa->spa_log_state = SPA_LOG_CLEAR;
8830 					error = 0;
8831 				}
8832 				mutex_exit(&spa_namespace_lock);
8833 
8834 				if (!error) {
8835 					error = spa_open_rewind(target, &spa,
8836 					    FTAG, policy, NULL);
8837 				}
8838 			}
8839 		} else if (strpbrk(target, "#") != NULL) {
8840 			dsl_pool_t *dp;
8841 			error = dsl_pool_hold(target, FTAG, &dp);
8842 			if (error != 0) {
8843 				fatal("can't dump '%s': %s", target,
8844 				    strerror(error));
8845 			}
8846 			error = dump_bookmark(dp, target, B_TRUE, verbose > 1);
8847 			dsl_pool_rele(dp, FTAG);
8848 			if (error != 0) {
8849 				fatal("can't dump '%s': %s", target,
8850 				    strerror(error));
8851 			}
8852 			return (error);
8853 		} else {
8854 			target_pool = strdup(target);
8855 			if (strpbrk(target, "/@") != NULL)
8856 				*strpbrk(target_pool, "/@") = '\0';
8857 
8858 			zdb_set_skip_mmp(target);
8859 			/*
8860 			 * If -N was supplied, the user has indicated that
8861 			 * zdb -d <pool>/<objsetID> is in effect.  Otherwise
8862 			 * we first assume that the dataset string is the
8863 			 * dataset name.  If dmu_objset_hold fails with the
8864 			 * dataset string, and we have an objset_id, retry the
8865 			 * lookup with the objsetID.
8866 			 */
8867 			boolean_t retry = B_TRUE;
8868 retry_lookup:
8869 			if (dataset_lookup == B_TRUE) {
8870 				/*
8871 				 * Use the supplied id to get the name
8872 				 * for open_objset.
8873 				 */
8874 				error = spa_open(target_pool, &spa, FTAG);
8875 				if (error == 0) {
8876 					error = name_from_objset_id(spa,
8877 					    objset_id, dsname);
8878 					spa_close(spa, FTAG);
8879 					if (error == 0)
8880 						target = dsname;
8881 				}
8882 			}
8883 			if (error == 0) {
8884 				if (objset_id > 0 && retry) {
8885 					int err = dmu_objset_hold(target, FTAG,
8886 					    &os);
8887 					if (err) {
8888 						dataset_lookup = B_TRUE;
8889 						retry = B_FALSE;
8890 						goto retry_lookup;
8891 					} else {
8892 						dmu_objset_rele(os, FTAG);
8893 					}
8894 				}
8895 				error = open_objset(target, FTAG, &os);
8896 			}
8897 			if (error == 0)
8898 				spa = dmu_objset_spa(os);
8899 			free(target_pool);
8900 		}
8901 	}
8902 	nvlist_free(policy);
8903 
8904 	if (error)
8905 		fatal("can't open '%s': %s", target, strerror(error));
8906 
8907 	/*
8908 	 * Set the pool failure mode to panic in order to prevent the pool
8909 	 * from suspending.  A suspended I/O will have no way to resume and
8910 	 * can prevent the zdb(8) command from terminating as expected.
8911 	 */
8912 	if (spa != NULL)
8913 		spa->spa_failmode = ZIO_FAILURE_MODE_PANIC;
8914 
8915 	argv++;
8916 	argc--;
8917 	if (dump_opt['r']) {
8918 		error = zdb_copy_object(os, object, argv[1]);
8919 	} else if (!dump_opt['R']) {
8920 		flagbits['d'] = ZOR_FLAG_DIRECTORY;
8921 		flagbits['f'] = ZOR_FLAG_PLAIN_FILE;
8922 		flagbits['m'] = ZOR_FLAG_SPACE_MAP;
8923 		flagbits['z'] = ZOR_FLAG_ZAP;
8924 		flagbits['A'] = ZOR_FLAG_ALL_TYPES;
8925 
8926 		if (argc > 0 && dump_opt['d']) {
8927 			zopt_object_args = argc;
8928 			zopt_object_ranges = calloc(zopt_object_args,
8929 			    sizeof (zopt_object_range_t));
8930 			for (unsigned i = 0; i < zopt_object_args; i++) {
8931 				int err;
8932 				char *msg = NULL;
8933 
8934 				err = parse_object_range(argv[i],
8935 				    &zopt_object_ranges[i], &msg);
8936 				if (err != 0)
8937 					fatal("Bad object or range: '%s': %s\n",
8938 					    argv[i], msg ? msg : "");
8939 			}
8940 		} else if (argc > 0 && dump_opt['m']) {
8941 			zopt_metaslab_args = argc;
8942 			zopt_metaslab = calloc(zopt_metaslab_args,
8943 			    sizeof (uint64_t));
8944 			for (unsigned i = 0; i < zopt_metaslab_args; i++) {
8945 				errno = 0;
8946 				zopt_metaslab[i] = strtoull(argv[i], NULL, 0);
8947 				if (zopt_metaslab[i] == 0 && errno != 0)
8948 					fatal("bad number %s: %s", argv[i],
8949 					    strerror(errno));
8950 			}
8951 		}
8952 		if (os != NULL) {
8953 			dump_objset(os);
8954 		} else if (zopt_object_args > 0 && !dump_opt['m']) {
8955 			dump_objset(spa->spa_meta_objset);
8956 		} else {
8957 			dump_zpool(spa);
8958 		}
8959 	} else {
8960 		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
8961 		flagbits['c'] = ZDB_FLAG_CHECKSUM;
8962 		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
8963 		flagbits['e'] = ZDB_FLAG_BSWAP;
8964 		flagbits['g'] = ZDB_FLAG_GBH;
8965 		flagbits['i'] = ZDB_FLAG_INDIRECT;
8966 		flagbits['r'] = ZDB_FLAG_RAW;
8967 		flagbits['v'] = ZDB_FLAG_VERBOSE;
8968 
8969 		for (int i = 0; i < argc; i++)
8970 			zdb_read_block(argv[i], spa);
8971 	}
8972 
8973 	if (dump_opt['k']) {
8974 		free(checkpoint_pool);
8975 		if (!target_is_spa)
8976 			free(checkpoint_target);
8977 	}
8978 
8979 	if (os != NULL) {
8980 		close_objset(os, FTAG);
8981 	} else {
8982 		spa_close(spa, FTAG);
8983 	}
8984 
8985 	fuid_table_destroy();
8986 
8987 	dump_debug_buffer();
8988 
8989 	kernel_fini();
8990 
8991 	return (error);
8992 }
8993