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