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