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