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