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