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