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