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