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