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