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