xref: /illumos-gate/usr/src/cmd/zdb/zdb.c (revision 4d7988d6)
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 2017 Nexenta Systems, Inc.
27  * Copyright (c) 2017, 2018 Lawrence Livermore National Security, LLC.
28  * Copyright 2017 RackTop Systems.
29  */
30 
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <stdio_ext.h>
34 #include <stdlib.h>
35 #include <ctype.h>
36 #include <sys/zfs_context.h>
37 #include <sys/spa.h>
38 #include <sys/spa_impl.h>
39 #include <sys/dmu.h>
40 #include <sys/zap.h>
41 #include <sys/fs/zfs.h>
42 #include <sys/zfs_znode.h>
43 #include <sys/zfs_sa.h>
44 #include <sys/sa.h>
45 #include <sys/sa_impl.h>
46 #include <sys/vdev.h>
47 #include <sys/vdev_impl.h>
48 #include <sys/metaslab_impl.h>
49 #include <sys/dmu_objset.h>
50 #include <sys/dsl_dir.h>
51 #include <sys/dsl_dataset.h>
52 #include <sys/dsl_pool.h>
53 #include <sys/dbuf.h>
54 #include <sys/zil.h>
55 #include <sys/zil_impl.h>
56 #include <sys/stat.h>
57 #include <sys/resource.h>
58 #include <sys/dmu_traverse.h>
59 #include <sys/zio_checksum.h>
60 #include <sys/zio_compress.h>
61 #include <sys/zfs_fuid.h>
62 #include <sys/arc.h>
63 #include <sys/ddt.h>
64 #include <sys/zfeature.h>
65 #include <sys/abd.h>
66 #include <sys/blkptr.h>
67 #include <sys/dsl_scan.h>
68 #include <sys/dsl_crypt.h>
69 #include <zfs_comutil.h>
70 #include <libcmdutils.h>
71 #undef verify
72 #include <libzfs.h>
73 
74 #include "zdb.h"
75 
76 #define	ZDB_COMPRESS_NAME(idx) ((idx) < ZIO_COMPRESS_FUNCTIONS ?	\
77 	zio_compress_table[(idx)].ci_name : "UNKNOWN")
78 #define	ZDB_CHECKSUM_NAME(idx) ((idx) < ZIO_CHECKSUM_FUNCTIONS ?	\
79 	zio_checksum_table[(idx)].ci_name : "UNKNOWN")
80 #define	ZDB_OT_NAME(idx) ((idx) < DMU_OT_NUMTYPES ?	\
81 	dmu_ot[(idx)].ot_name : DMU_OT_IS_VALID(idx) ?	\
82 	dmu_ot_byteswap[DMU_OT_BYTESWAP(idx)].ob_name : "UNKNOWN")
83 #define	ZDB_OT_TYPE(idx) ((idx) < DMU_OT_NUMTYPES ? (idx) :		\
84 	(idx) == DMU_OTN_ZAP_DATA || (idx) == DMU_OTN_ZAP_METADATA ?	\
85 	DMU_OT_ZAP_OTHER : \
86 	(idx) == DMU_OTN_UINT64_DATA || (idx) == DMU_OTN_UINT64_METADATA ? \
87 	DMU_OT_UINT64_OTHER : DMU_OT_NUMTYPES)
88 
89 extern int reference_tracking_enable;
90 extern boolean_t zfs_recover;
91 extern uint64_t zfs_arc_max, zfs_arc_meta_limit;
92 extern int zfs_vdev_async_read_max_active;
93 extern int aok;
94 extern boolean_t spa_load_verify_dryrun;
95 extern int zfs_btree_verify_intensity;
96 
97 static const char cmdname[] = "zdb";
98 uint8_t dump_opt[256];
99 
100 typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
101 
102 uint64_t *zopt_object = NULL;
103 static unsigned zopt_objects = 0;
104 libzfs_handle_t *g_zfs;
105 uint64_t max_inflight = 1000;
106 static int leaked_objects = 0;
107 
108 static void snprintf_blkptr_compact(char *, size_t, const blkptr_t *);
109 static void mos_obj_refd(uint64_t);
110 
111 /*
112  * These libumem hooks provide a reasonable set of defaults for the allocator's
113  * debugging facilities.
114  */
115 const char *
116 _umem_debug_init()
117 {
118 	return ("default,verbose"); /* $UMEM_DEBUG setting */
119 }
120 
121 const char *
122 _umem_logging_init(void)
123 {
124 	return ("fail,contents"); /* $UMEM_LOGGING setting */
125 }
126 
127 static void
128 usage(void)
129 {
130 	(void) fprintf(stderr,
131 	    "Usage:\t%s [-AbcdDFGhikLMPsvX] [-e [-V] [-p <path> ...]] "
132 	    "[-I <inflight I/Os>]\n"
133 	    "\t\t[-o <var>=<value>]... [-t <txg>] [-U <cache>] [-x <dumpdir>]\n"
134 	    "\t\t[<poolname> [<object> ...]]\n"
135 	    "\t%s [-AdiPv] [-e [-V] [-p <path> ...]] [-U <cache>] <dataset> "
136 	    "[<object> ...]\n"
137 	    "\t%s -C [-A] [-U <cache>]\n"
138 	    "\t%s -l [-Aqu] <device>\n"
139 	    "\t%s -m [-AFLPX] [-e [-V] [-p <path> ...]] [-t <txg>] "
140 	    "[-U <cache>]\n\t\t<poolname> [<vdev> [<metaslab> ...]]\n"
141 	    "\t%s -O <dataset> <path>\n"
142 	    "\t%s -R [-A] [-e [-V] [-p <path> ...]] [-U <cache>]\n"
143 	    "\t\t<poolname> <vdev>:<offset>:<size>[:<flags>]\n"
144 	    "\t%s -E [-A] word0:word1:...:word15\n"
145 	    "\t%s -S [-AP] [-e [-V] [-p <path> ...]] [-U <cache>] "
146 	    "<poolname>\n\n",
147 	    cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname,
148 	    cmdname, cmdname);
149 
150 	(void) fprintf(stderr, "    Dataset name must include at least one "
151 	    "separator character '/' or '@'\n");
152 	(void) fprintf(stderr, "    If dataset name is specified, only that "
153 	    "dataset is dumped\n");
154 	(void) fprintf(stderr, "    If object numbers are specified, only "
155 	    "those objects are dumped\n\n");
156 	(void) fprintf(stderr, "    Options to control amount of output:\n");
157 	(void) fprintf(stderr, "        -b block statistics\n");
158 	(void) fprintf(stderr, "        -c checksum all metadata (twice for "
159 	    "all data) blocks\n");
160 	(void) fprintf(stderr, "        -C config (or cachefile if alone)\n");
161 	(void) fprintf(stderr, "        -d dataset(s)\n");
162 	(void) fprintf(stderr, "        -D dedup statistics\n");
163 	(void) fprintf(stderr, "        -E decode and display block from an "
164 	    "embedded block pointer\n");
165 	(void) fprintf(stderr, "        -h pool history\n");
166 	(void) fprintf(stderr, "        -i intent logs\n");
167 	(void) fprintf(stderr, "        -l read label contents\n");
168 	(void) fprintf(stderr, "        -k examine the checkpointed state "
169 	    "of the pool\n");
170 	(void) fprintf(stderr, "        -L disable leak tracking (do not "
171 	    "load spacemaps)\n");
172 	(void) fprintf(stderr, "        -m metaslabs\n");
173 	(void) fprintf(stderr, "        -M metaslab groups\n");
174 	(void) fprintf(stderr, "        -O perform object lookups by path\n");
175 	(void) fprintf(stderr, "        -R read and display block from a "
176 	    "device\n");
177 	(void) fprintf(stderr, "        -s report stats on zdb's I/O\n");
178 	(void) fprintf(stderr, "        -S simulate dedup to measure effect\n");
179 	(void) fprintf(stderr, "        -v verbose (applies to all "
180 	    "others)\n\n");
181 	(void) fprintf(stderr, "    Below options are intended for use "
182 	    "with other options:\n");
183 	(void) fprintf(stderr, "        -A ignore assertions (-A), enable "
184 	    "panic recovery (-AA) or both (-AAA)\n");
185 	(void) fprintf(stderr, "        -e pool is exported/destroyed/"
186 	    "has altroot/not in a cachefile\n");
187 	(void) fprintf(stderr, "        -F attempt automatic rewind within "
188 	    "safe range of transaction groups\n");
189 	(void) fprintf(stderr, "        -G dump zfs_dbgmsg buffer before "
190 	    "exiting\n");
191 	(void) fprintf(stderr, "        -I <number of inflight I/Os> -- "
192 	    "specify the maximum number of "
193 	    "checksumming I/Os [default is 200]\n");
194 	(void) fprintf(stderr, "        -o <variable>=<value> set global "
195 	    "variable to an unsigned 32-bit integer value\n");
196 	(void) fprintf(stderr, "        -p <path> -- use one or more with "
197 	    "-e to specify path to vdev dir\n");
198 	(void) fprintf(stderr, "        -P print numbers in parseable form\n");
199 	(void) fprintf(stderr, "        -q don't print label contents\n");
200 	(void) fprintf(stderr, "        -t <txg> -- highest txg to use when "
201 	    "searching for uberblocks\n");
202 	(void) fprintf(stderr, "        -u uberblock\n");
203 	(void) fprintf(stderr, "        -U <cachefile_path> -- use alternate "
204 	    "cachefile\n");
205 	(void) fprintf(stderr, "        -V do verbatim import\n");
206 	(void) fprintf(stderr, "        -x <dumpdir> -- "
207 	    "dump all read blocks into specified directory\n");
208 	(void) fprintf(stderr, "        -X attempt extreme rewind (does not "
209 	    "work with dataset)\n\n");
210 	(void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
211 	    "to make only that option verbose\n");
212 	(void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
213 	exit(1);
214 }
215 
216 static void
217 dump_debug_buffer()
218 {
219 	if (dump_opt['G']) {
220 		(void) printf("\n");
221 		zfs_dbgmsg_print("zdb");
222 	}
223 }
224 
225 /*
226  * Called for usage errors that are discovered after a call to spa_open(),
227  * dmu_bonus_hold(), or pool_match().  abort() is called for other errors.
228  */
229 
230 static void
231 fatal(const char *fmt, ...)
232 {
233 	va_list ap;
234 
235 	va_start(ap, fmt);
236 	(void) fprintf(stderr, "%s: ", cmdname);
237 	(void) vfprintf(stderr, fmt, ap);
238 	va_end(ap);
239 	(void) fprintf(stderr, "\n");
240 
241 	dump_debug_buffer();
242 
243 	exit(1);
244 }
245 
246 /* ARGSUSED */
247 static void
248 dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
249 {
250 	nvlist_t *nv;
251 	size_t nvsize = *(uint64_t *)data;
252 	char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
253 
254 	VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
255 
256 	VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
257 
258 	umem_free(packed, nvsize);
259 
260 	dump_nvlist(nv, 8);
261 
262 	nvlist_free(nv);
263 }
264 
265 /* ARGSUSED */
266 static void
267 dump_history_offsets(objset_t *os, uint64_t object, void *data, size_t size)
268 {
269 	spa_history_phys_t *shp = data;
270 
271 	if (shp == NULL)
272 		return;
273 
274 	(void) printf("\t\tpool_create_len = %llu\n",
275 	    (u_longlong_t)shp->sh_pool_create_len);
276 	(void) printf("\t\tphys_max_off = %llu\n",
277 	    (u_longlong_t)shp->sh_phys_max_off);
278 	(void) printf("\t\tbof = %llu\n",
279 	    (u_longlong_t)shp->sh_bof);
280 	(void) printf("\t\teof = %llu\n",
281 	    (u_longlong_t)shp->sh_eof);
282 	(void) printf("\t\trecords_lost = %llu\n",
283 	    (u_longlong_t)shp->sh_records_lost);
284 }
285 
286 static void
287 zdb_nicenum(uint64_t num, char *buf, size_t buflen)
288 {
289 	if (dump_opt['P'])
290 		(void) snprintf(buf, buflen, "%llu", (longlong_t)num);
291 	else
292 		nicenum(num, buf, sizeof (buf));
293 }
294 
295 static const char histo_stars[] = "****************************************";
296 static const uint64_t histo_width = sizeof (histo_stars) - 1;
297 
298 static void
299 dump_histogram(const uint64_t *histo, int size, int offset)
300 {
301 	int i;
302 	int minidx = size - 1;
303 	int maxidx = 0;
304 	uint64_t max = 0;
305 
306 	for (i = 0; i < size; i++) {
307 		if (histo[i] > max)
308 			max = histo[i];
309 		if (histo[i] > 0 && i > maxidx)
310 			maxidx = i;
311 		if (histo[i] > 0 && i < minidx)
312 			minidx = i;
313 	}
314 
315 	if (max < histo_width)
316 		max = histo_width;
317 
318 	for (i = minidx; i <= maxidx; i++) {
319 		(void) printf("\t\t\t%3u: %6llu %s\n",
320 		    i + offset, (u_longlong_t)histo[i],
321 		    &histo_stars[(max - histo[i]) * histo_width / max]);
322 	}
323 }
324 
325 static void
326 dump_zap_stats(objset_t *os, uint64_t object)
327 {
328 	int error;
329 	zap_stats_t zs;
330 
331 	error = zap_get_stats(os, object, &zs);
332 	if (error)
333 		return;
334 
335 	if (zs.zs_ptrtbl_len == 0) {
336 		ASSERT(zs.zs_num_blocks == 1);
337 		(void) printf("\tmicrozap: %llu bytes, %llu entries\n",
338 		    (u_longlong_t)zs.zs_blocksize,
339 		    (u_longlong_t)zs.zs_num_entries);
340 		return;
341 	}
342 
343 	(void) printf("\tFat ZAP stats:\n");
344 
345 	(void) printf("\t\tPointer table:\n");
346 	(void) printf("\t\t\t%llu elements\n",
347 	    (u_longlong_t)zs.zs_ptrtbl_len);
348 	(void) printf("\t\t\tzt_blk: %llu\n",
349 	    (u_longlong_t)zs.zs_ptrtbl_zt_blk);
350 	(void) printf("\t\t\tzt_numblks: %llu\n",
351 	    (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
352 	(void) printf("\t\t\tzt_shift: %llu\n",
353 	    (u_longlong_t)zs.zs_ptrtbl_zt_shift);
354 	(void) printf("\t\t\tzt_blks_copied: %llu\n",
355 	    (u_longlong_t)zs.zs_ptrtbl_blks_copied);
356 	(void) printf("\t\t\tzt_nextblk: %llu\n",
357 	    (u_longlong_t)zs.zs_ptrtbl_nextblk);
358 
359 	(void) printf("\t\tZAP entries: %llu\n",
360 	    (u_longlong_t)zs.zs_num_entries);
361 	(void) printf("\t\tLeaf blocks: %llu\n",
362 	    (u_longlong_t)zs.zs_num_leafs);
363 	(void) printf("\t\tTotal blocks: %llu\n",
364 	    (u_longlong_t)zs.zs_num_blocks);
365 	(void) printf("\t\tzap_block_type: 0x%llx\n",
366 	    (u_longlong_t)zs.zs_block_type);
367 	(void) printf("\t\tzap_magic: 0x%llx\n",
368 	    (u_longlong_t)zs.zs_magic);
369 	(void) printf("\t\tzap_salt: 0x%llx\n",
370 	    (u_longlong_t)zs.zs_salt);
371 
372 	(void) printf("\t\tLeafs with 2^n pointers:\n");
373 	dump_histogram(zs.zs_leafs_with_2n_pointers, ZAP_HISTOGRAM_SIZE, 0);
374 
375 	(void) printf("\t\tBlocks with n*5 entries:\n");
376 	dump_histogram(zs.zs_blocks_with_n5_entries, ZAP_HISTOGRAM_SIZE, 0);
377 
378 	(void) printf("\t\tBlocks n/10 full:\n");
379 	dump_histogram(zs.zs_blocks_n_tenths_full, ZAP_HISTOGRAM_SIZE, 0);
380 
381 	(void) printf("\t\tEntries with n chunks:\n");
382 	dump_histogram(zs.zs_entries_using_n_chunks, ZAP_HISTOGRAM_SIZE, 0);
383 
384 	(void) printf("\t\tBuckets with n entries:\n");
385 	dump_histogram(zs.zs_buckets_with_n_entries, ZAP_HISTOGRAM_SIZE, 0);
386 }
387 
388 /*ARGSUSED*/
389 static void
390 dump_none(objset_t *os, uint64_t object, void *data, size_t size)
391 {
392 }
393 
394 /*ARGSUSED*/
395 static void
396 dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
397 {
398 	(void) printf("\tUNKNOWN OBJECT TYPE\n");
399 }
400 
401 /*ARGSUSED*/
402 static void
403 dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
404 {
405 }
406 
407 /*ARGSUSED*/
408 static void
409 dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
410 {
411 }
412 
413 /*ARGSUSED*/
414 static void
415 dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
416 {
417 	zap_cursor_t zc;
418 	zap_attribute_t attr;
419 	void *prop;
420 	unsigned i;
421 
422 	dump_zap_stats(os, object);
423 	(void) printf("\n");
424 
425 	for (zap_cursor_init(&zc, os, object);
426 	    zap_cursor_retrieve(&zc, &attr) == 0;
427 	    zap_cursor_advance(&zc)) {
428 		(void) printf("\t\t%s = ", attr.za_name);
429 		if (attr.za_num_integers == 0) {
430 			(void) printf("\n");
431 			continue;
432 		}
433 		prop = umem_zalloc(attr.za_num_integers *
434 		    attr.za_integer_length, UMEM_NOFAIL);
435 		(void) zap_lookup(os, object, attr.za_name,
436 		    attr.za_integer_length, attr.za_num_integers, prop);
437 		if (attr.za_integer_length == 1) {
438 			if (strcmp(attr.za_name,
439 			    DSL_CRYPTO_KEY_MASTER_KEY) == 0 ||
440 			    strcmp(attr.za_name,
441 			    DSL_CRYPTO_KEY_HMAC_KEY) == 0 ||
442 			    strcmp(attr.za_name, DSL_CRYPTO_KEY_IV) == 0 ||
443 			    strcmp(attr.za_name, DSL_CRYPTO_KEY_MAC) == 0 ||
444 			    strcmp(attr.za_name, DMU_POOL_CHECKSUM_SALT) == 0) {
445 				uint8_t *u8 = prop;
446 
447 				for (i = 0; i < attr.za_num_integers; i++) {
448 					(void) printf("%02x", u8[i]);
449 				}
450 			} else {
451 				(void) printf("%s", (char *)prop);
452 			}
453 		} else {
454 			for (i = 0; i < attr.za_num_integers; i++) {
455 				switch (attr.za_integer_length) {
456 				case 2:
457 					(void) printf("%u ",
458 					    ((uint16_t *)prop)[i]);
459 					break;
460 				case 4:
461 					(void) printf("%u ",
462 					    ((uint32_t *)prop)[i]);
463 					break;
464 				case 8:
465 					(void) printf("%lld ",
466 					    (u_longlong_t)((int64_t *)prop)[i]);
467 					break;
468 				}
469 			}
470 		}
471 		(void) printf("\n");
472 		umem_free(prop, attr.za_num_integers * attr.za_integer_length);
473 	}
474 	zap_cursor_fini(&zc);
475 }
476 
477 static void
478 dump_bpobj(objset_t *os, uint64_t object, void *data, size_t size)
479 {
480 	bpobj_phys_t *bpop = data;
481 	char bytes[32], comp[32], uncomp[32];
482 
483 	/* make sure the output won't get truncated */
484 	CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
485 	CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
486 	CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
487 
488 	if (bpop == NULL)
489 		return;
490 
491 	zdb_nicenum(bpop->bpo_bytes, bytes, sizeof (bytes));
492 	zdb_nicenum(bpop->bpo_comp, comp, sizeof (comp));
493 	zdb_nicenum(bpop->bpo_uncomp, uncomp, sizeof (uncomp));
494 
495 	(void) printf("\t\tnum_blkptrs = %llu\n",
496 	    (u_longlong_t)bpop->bpo_num_blkptrs);
497 	(void) printf("\t\tbytes = %s\n", bytes);
498 	if (size >= BPOBJ_SIZE_V1) {
499 		(void) printf("\t\tcomp = %s\n", comp);
500 		(void) printf("\t\tuncomp = %s\n", uncomp);
501 	}
502 	if (size >= sizeof (*bpop)) {
503 		(void) printf("\t\tsubobjs = %llu\n",
504 		    (u_longlong_t)bpop->bpo_subobjs);
505 		(void) printf("\t\tnum_subobjs = %llu\n",
506 		    (u_longlong_t)bpop->bpo_num_subobjs);
507 	}
508 
509 	if (dump_opt['d'] < 5)
510 		return;
511 
512 	for (uint64_t i = 0; i < bpop->bpo_num_blkptrs; i++) {
513 		char blkbuf[BP_SPRINTF_LEN];
514 		blkptr_t bp;
515 
516 		int err = dmu_read(os, object,
517 		    i * sizeof (bp), sizeof (bp), &bp, 0);
518 		if (err != 0) {
519 			(void) printf("got error %u from dmu_read\n", err);
520 			break;
521 		}
522 		snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), &bp);
523 		(void) printf("\t%s\n", blkbuf);
524 	}
525 }
526 
527 /* ARGSUSED */
528 static void
529 dump_bpobj_subobjs(objset_t *os, uint64_t object, void *data, size_t size)
530 {
531 	dmu_object_info_t doi;
532 
533 	VERIFY0(dmu_object_info(os, object, &doi));
534 	uint64_t *subobjs = kmem_alloc(doi.doi_max_offset, KM_SLEEP);
535 
536 	int err = dmu_read(os, object, 0, doi.doi_max_offset, subobjs, 0);
537 	if (err != 0) {
538 		(void) printf("got error %u from dmu_read\n", err);
539 		kmem_free(subobjs, doi.doi_max_offset);
540 		return;
541 	}
542 
543 	int64_t last_nonzero = -1;
544 	for (uint64_t i = 0; i < doi.doi_max_offset / 8; i++) {
545 		if (subobjs[i] != 0)
546 			last_nonzero = i;
547 	}
548 
549 	for (int64_t i = 0; i <= last_nonzero; i++) {
550 		(void) printf("\t%llu\n", (longlong_t)subobjs[i]);
551 	}
552 	kmem_free(subobjs, doi.doi_max_offset);
553 }
554 
555 /*ARGSUSED*/
556 static void
557 dump_ddt_zap(objset_t *os, uint64_t object, void *data, size_t size)
558 {
559 	dump_zap_stats(os, object);
560 	/* contents are printed elsewhere, properly decoded */
561 }
562 
563 /*ARGSUSED*/
564 static void
565 dump_sa_attrs(objset_t *os, uint64_t object, void *data, size_t size)
566 {
567 	zap_cursor_t zc;
568 	zap_attribute_t attr;
569 
570 	dump_zap_stats(os, object);
571 	(void) printf("\n");
572 
573 	for (zap_cursor_init(&zc, os, object);
574 	    zap_cursor_retrieve(&zc, &attr) == 0;
575 	    zap_cursor_advance(&zc)) {
576 		(void) printf("\t\t%s = ", attr.za_name);
577 		if (attr.za_num_integers == 0) {
578 			(void) printf("\n");
579 			continue;
580 		}
581 		(void) printf(" %llx : [%d:%d:%d]\n",
582 		    (u_longlong_t)attr.za_first_integer,
583 		    (int)ATTR_LENGTH(attr.za_first_integer),
584 		    (int)ATTR_BSWAP(attr.za_first_integer),
585 		    (int)ATTR_NUM(attr.za_first_integer));
586 	}
587 	zap_cursor_fini(&zc);
588 }
589 
590 /*ARGSUSED*/
591 static void
592 dump_sa_layouts(objset_t *os, uint64_t object, void *data, size_t size)
593 {
594 	zap_cursor_t zc;
595 	zap_attribute_t attr;
596 	uint16_t *layout_attrs;
597 	unsigned i;
598 
599 	dump_zap_stats(os, object);
600 	(void) printf("\n");
601 
602 	for (zap_cursor_init(&zc, os, object);
603 	    zap_cursor_retrieve(&zc, &attr) == 0;
604 	    zap_cursor_advance(&zc)) {
605 		(void) printf("\t\t%s = [", attr.za_name);
606 		if (attr.za_num_integers == 0) {
607 			(void) printf("\n");
608 			continue;
609 		}
610 
611 		VERIFY(attr.za_integer_length == 2);
612 		layout_attrs = umem_zalloc(attr.za_num_integers *
613 		    attr.za_integer_length, UMEM_NOFAIL);
614 
615 		VERIFY(zap_lookup(os, object, attr.za_name,
616 		    attr.za_integer_length,
617 		    attr.za_num_integers, layout_attrs) == 0);
618 
619 		for (i = 0; i != attr.za_num_integers; i++)
620 			(void) printf(" %d ", (int)layout_attrs[i]);
621 		(void) printf("]\n");
622 		umem_free(layout_attrs,
623 		    attr.za_num_integers * attr.za_integer_length);
624 	}
625 	zap_cursor_fini(&zc);
626 }
627 
628 /*ARGSUSED*/
629 static void
630 dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
631 {
632 	zap_cursor_t zc;
633 	zap_attribute_t attr;
634 	const char *typenames[] = {
635 		/* 0 */ "not specified",
636 		/* 1 */ "FIFO",
637 		/* 2 */ "Character Device",
638 		/* 3 */ "3 (invalid)",
639 		/* 4 */ "Directory",
640 		/* 5 */ "5 (invalid)",
641 		/* 6 */ "Block Device",
642 		/* 7 */ "7 (invalid)",
643 		/* 8 */ "Regular File",
644 		/* 9 */ "9 (invalid)",
645 		/* 10 */ "Symbolic Link",
646 		/* 11 */ "11 (invalid)",
647 		/* 12 */ "Socket",
648 		/* 13 */ "Door",
649 		/* 14 */ "Event Port",
650 		/* 15 */ "15 (invalid)",
651 	};
652 
653 	dump_zap_stats(os, object);
654 	(void) printf("\n");
655 
656 	for (zap_cursor_init(&zc, os, object);
657 	    zap_cursor_retrieve(&zc, &attr) == 0;
658 	    zap_cursor_advance(&zc)) {
659 		(void) printf("\t\t%s = %lld (type: %s)\n",
660 		    attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
661 		    typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
662 	}
663 	zap_cursor_fini(&zc);
664 }
665 
666 static int
667 get_dtl_refcount(vdev_t *vd)
668 {
669 	int refcount = 0;
670 
671 	if (vd->vdev_ops->vdev_op_leaf) {
672 		space_map_t *sm = vd->vdev_dtl_sm;
673 
674 		if (sm != NULL &&
675 		    sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
676 			return (1);
677 		return (0);
678 	}
679 
680 	for (unsigned c = 0; c < vd->vdev_children; c++)
681 		refcount += get_dtl_refcount(vd->vdev_child[c]);
682 	return (refcount);
683 }
684 
685 static int
686 get_metaslab_refcount(vdev_t *vd)
687 {
688 	int refcount = 0;
689 
690 	if (vd->vdev_top == vd) {
691 		for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
692 			space_map_t *sm = vd->vdev_ms[m]->ms_sm;
693 
694 			if (sm != NULL &&
695 			    sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
696 				refcount++;
697 		}
698 	}
699 	for (unsigned c = 0; c < vd->vdev_children; c++)
700 		refcount += get_metaslab_refcount(vd->vdev_child[c]);
701 
702 	return (refcount);
703 }
704 
705 static int
706 get_obsolete_refcount(vdev_t *vd)
707 {
708 	int refcount = 0;
709 
710 	uint64_t obsolete_sm_obj = vdev_obsolete_sm_object(vd);
711 	if (vd->vdev_top == vd && obsolete_sm_obj != 0) {
712 		dmu_object_info_t doi;
713 		VERIFY0(dmu_object_info(vd->vdev_spa->spa_meta_objset,
714 		    obsolete_sm_obj, &doi));
715 		if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
716 			refcount++;
717 		}
718 	} else {
719 		ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
720 		ASSERT3U(obsolete_sm_obj, ==, 0);
721 	}
722 	for (unsigned c = 0; c < vd->vdev_children; c++) {
723 		refcount += get_obsolete_refcount(vd->vdev_child[c]);
724 	}
725 
726 	return (refcount);
727 }
728 
729 static int
730 get_prev_obsolete_spacemap_refcount(spa_t *spa)
731 {
732 	uint64_t prev_obj =
733 	    spa->spa_condensing_indirect_phys.scip_prev_obsolete_sm_object;
734 	if (prev_obj != 0) {
735 		dmu_object_info_t doi;
736 		VERIFY0(dmu_object_info(spa->spa_meta_objset, prev_obj, &doi));
737 		if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
738 			return (1);
739 		}
740 	}
741 	return (0);
742 }
743 
744 static int
745 get_checkpoint_refcount(vdev_t *vd)
746 {
747 	int refcount = 0;
748 
749 	if (vd->vdev_top == vd && vd->vdev_top_zap != 0 &&
750 	    zap_contains(spa_meta_objset(vd->vdev_spa),
751 	    vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) == 0)
752 		refcount++;
753 
754 	for (uint64_t c = 0; c < vd->vdev_children; c++)
755 		refcount += get_checkpoint_refcount(vd->vdev_child[c]);
756 
757 	return (refcount);
758 }
759 
760 static int
761 get_log_spacemap_refcount(spa_t *spa)
762 {
763 	return (avl_numnodes(&spa->spa_sm_logs_by_txg));
764 }
765 
766 static int
767 verify_spacemap_refcounts(spa_t *spa)
768 {
769 	uint64_t expected_refcount = 0;
770 	uint64_t actual_refcount;
771 
772 	(void) feature_get_refcount(spa,
773 	    &spa_feature_table[SPA_FEATURE_SPACEMAP_HISTOGRAM],
774 	    &expected_refcount);
775 	actual_refcount = get_dtl_refcount(spa->spa_root_vdev);
776 	actual_refcount += get_metaslab_refcount(spa->spa_root_vdev);
777 	actual_refcount += get_obsolete_refcount(spa->spa_root_vdev);
778 	actual_refcount += get_prev_obsolete_spacemap_refcount(spa);
779 	actual_refcount += get_checkpoint_refcount(spa->spa_root_vdev);
780 	actual_refcount += get_log_spacemap_refcount(spa);
781 
782 	if (expected_refcount != actual_refcount) {
783 		(void) printf("space map refcount mismatch: expected %lld != "
784 		    "actual %lld\n",
785 		    (longlong_t)expected_refcount,
786 		    (longlong_t)actual_refcount);
787 		return (2);
788 	}
789 	return (0);
790 }
791 
792 static void
793 dump_spacemap(objset_t *os, space_map_t *sm)
794 {
795 	char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
796 	    "INVALID", "INVALID", "INVALID", "INVALID" };
797 
798 	if (sm == NULL)
799 		return;
800 
801 	(void) printf("space map object %llu:\n",
802 	    (longlong_t)sm->sm_object);
803 	(void) printf("  smp_length = 0x%llx\n",
804 	    (longlong_t)sm->sm_phys->smp_length);
805 	(void) printf("  smp_alloc = 0x%llx\n",
806 	    (longlong_t)sm->sm_phys->smp_alloc);
807 
808 	if (dump_opt['d'] < 6 && dump_opt['m'] < 4)
809 		return;
810 
811 	/*
812 	 * Print out the freelist entries in both encoded and decoded form.
813 	 */
814 	uint8_t mapshift = sm->sm_shift;
815 	int64_t alloc = 0;
816 	uint64_t word, entry_id = 0;
817 	for (uint64_t offset = 0; offset < space_map_length(sm);
818 	    offset += sizeof (word)) {
819 
820 		VERIFY0(dmu_read(os, space_map_object(sm), offset,
821 		    sizeof (word), &word, DMU_READ_PREFETCH));
822 
823 		if (sm_entry_is_debug(word)) {
824 			(void) printf("\t    [%6llu] %s: txg %llu pass %llu\n",
825 			    (u_longlong_t)entry_id,
826 			    ddata[SM_DEBUG_ACTION_DECODE(word)],
827 			    (u_longlong_t)SM_DEBUG_TXG_DECODE(word),
828 			    (u_longlong_t)SM_DEBUG_SYNCPASS_DECODE(word));
829 			entry_id++;
830 			continue;
831 		}
832 
833 		uint8_t words;
834 		char entry_type;
835 		uint64_t entry_off, entry_run, entry_vdev = SM_NO_VDEVID;
836 
837 		if (sm_entry_is_single_word(word)) {
838 			entry_type = (SM_TYPE_DECODE(word) == SM_ALLOC) ?
839 			    'A' : 'F';
840 			entry_off = (SM_OFFSET_DECODE(word) << mapshift) +
841 			    sm->sm_start;
842 			entry_run = SM_RUN_DECODE(word) << mapshift;
843 			words = 1;
844 		} else {
845 			/* it is a two-word entry so we read another word */
846 			ASSERT(sm_entry_is_double_word(word));
847 
848 			uint64_t extra_word;
849 			offset += sizeof (extra_word);
850 			VERIFY0(dmu_read(os, space_map_object(sm), offset,
851 			    sizeof (extra_word), &extra_word,
852 			    DMU_READ_PREFETCH));
853 
854 			ASSERT3U(offset, <=, space_map_length(sm));
855 
856 			entry_run = SM2_RUN_DECODE(word) << mapshift;
857 			entry_vdev = SM2_VDEV_DECODE(word);
858 			entry_type = (SM2_TYPE_DECODE(extra_word) == SM_ALLOC) ?
859 			    'A' : 'F';
860 			entry_off = (SM2_OFFSET_DECODE(extra_word) <<
861 			    mapshift) + sm->sm_start;
862 			words = 2;
863 		}
864 
865 		(void) printf("\t    [%6llu]    %c  range:"
866 		    " %010llx-%010llx  size: %06llx vdev: %06llu words: %u\n",
867 		    (u_longlong_t)entry_id,
868 		    entry_type, (u_longlong_t)entry_off,
869 		    (u_longlong_t)(entry_off + entry_run),
870 		    (u_longlong_t)entry_run,
871 		    (u_longlong_t)entry_vdev, words);
872 
873 		if (entry_type == 'A')
874 			alloc += entry_run;
875 		else
876 			alloc -= entry_run;
877 		entry_id++;
878 	}
879 	if (alloc != space_map_allocated(sm)) {
880 		(void) printf("space_map_object alloc (%lld) INCONSISTENT "
881 		    "with space map summary (%lld)\n",
882 		    (longlong_t)space_map_allocated(sm), (longlong_t)alloc);
883 	}
884 }
885 
886 static void
887 dump_metaslab_stats(metaslab_t *msp)
888 {
889 	char maxbuf[32];
890 	range_tree_t *rt = msp->ms_allocatable;
891 	zfs_btree_t *t = &msp->ms_allocatable_by_size;
892 	int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
893 
894 	/* max sure nicenum has enough space */
895 	CTASSERT(sizeof (maxbuf) >= NN_NUMBUF_SZ);
896 
897 	zdb_nicenum(metaslab_largest_allocatable(msp), maxbuf, sizeof (maxbuf));
898 
899 	(void) printf("\t %25s %10lu   %7s  %6s   %4s %4d%%\n",
900 	    "segments", zfs_btree_numnodes(t), "maxsize", maxbuf,
901 	    "freepct", free_pct);
902 	(void) printf("\tIn-memory histogram:\n");
903 	dump_histogram(rt->rt_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
904 }
905 
906 static void
907 dump_metaslab(metaslab_t *msp)
908 {
909 	vdev_t *vd = msp->ms_group->mg_vd;
910 	spa_t *spa = vd->vdev_spa;
911 	space_map_t *sm = msp->ms_sm;
912 	char freebuf[32];
913 
914 	zdb_nicenum(msp->ms_size - space_map_allocated(sm), freebuf,
915 	    sizeof (freebuf));
916 
917 	(void) printf(
918 	    "\tmetaslab %6llu   offset %12llx   spacemap %6llu   free    %5s\n",
919 	    (u_longlong_t)msp->ms_id, (u_longlong_t)msp->ms_start,
920 	    (u_longlong_t)space_map_object(sm), freebuf);
921 
922 	if (dump_opt['m'] > 2 && !dump_opt['L']) {
923 		mutex_enter(&msp->ms_lock);
924 		VERIFY0(metaslab_load(msp));
925 		range_tree_stat_verify(msp->ms_allocatable);
926 		dump_metaslab_stats(msp);
927 		metaslab_unload(msp);
928 		mutex_exit(&msp->ms_lock);
929 	}
930 
931 	if (dump_opt['m'] > 1 && sm != NULL &&
932 	    spa_feature_is_active(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
933 		/*
934 		 * The space map histogram represents free space in chunks
935 		 * of sm_shift (i.e. bucket 0 refers to 2^sm_shift).
936 		 */
937 		(void) printf("\tOn-disk histogram:\t\tfragmentation %llu\n",
938 		    (u_longlong_t)msp->ms_fragmentation);
939 		dump_histogram(sm->sm_phys->smp_histogram,
940 		    SPACE_MAP_HISTOGRAM_SIZE, sm->sm_shift);
941 	}
942 
943 	ASSERT(msp->ms_size == (1ULL << vd->vdev_ms_shift));
944 	dump_spacemap(spa->spa_meta_objset, msp->ms_sm);
945 
946 	if (spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP)) {
947 		(void) printf("\tFlush data:\n\tunflushed txg=%llu\n\n",
948 		    (u_longlong_t)metaslab_unflushed_txg(msp));
949 	}
950 }
951 
952 static void
953 print_vdev_metaslab_header(vdev_t *vd)
954 {
955 	vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
956 	const char *bias_str = "";
957 
958 	if (alloc_bias == VDEV_BIAS_LOG || vd->vdev_islog) {
959 		bias_str = VDEV_ALLOC_BIAS_LOG;
960 	} else if (alloc_bias == VDEV_BIAS_SPECIAL) {
961 		bias_str = VDEV_ALLOC_BIAS_SPECIAL;
962 	} else if (alloc_bias == VDEV_BIAS_DEDUP) {
963 		bias_str = VDEV_ALLOC_BIAS_DEDUP;
964 	}
965 
966 	uint64_t ms_flush_data_obj = 0;
967 	if (vd->vdev_top_zap != 0) {
968 		int error = zap_lookup(spa_meta_objset(vd->vdev_spa),
969 		    vd->vdev_top_zap, VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS,
970 		    sizeof (uint64_t), 1, &ms_flush_data_obj);
971 		if (error != ENOENT) {
972 			ASSERT0(error);
973 		}
974 	}
975 
976 	(void) printf("\tvdev %10llu   %s",
977 	    (u_longlong_t)vd->vdev_id, bias_str);
978 
979 	if (ms_flush_data_obj != 0) {
980 		(void) printf("   ms_unflushed_phys object %llu",
981 		    (u_longlong_t)ms_flush_data_obj);
982 	}
983 
984 	(void) printf("\n\t%-10s%5llu   %-19s   %-15s   %-12s\n",
985 	    "metaslabs", (u_longlong_t)vd->vdev_ms_count,
986 	    "offset", "spacemap", "free");
987 	(void) printf("\t%15s   %19s   %15s   %12s\n",
988 	    "---------------", "-------------------",
989 	    "---------------", "------------");
990 }
991 
992 static void
993 dump_metaslab_groups(spa_t *spa)
994 {
995 	vdev_t *rvd = spa->spa_root_vdev;
996 	metaslab_class_t *mc = spa_normal_class(spa);
997 	uint64_t fragmentation;
998 
999 	metaslab_class_histogram_verify(mc);
1000 
1001 	for (unsigned c = 0; c < rvd->vdev_children; c++) {
1002 		vdev_t *tvd = rvd->vdev_child[c];
1003 		metaslab_group_t *mg = tvd->vdev_mg;
1004 
1005 		if (mg == NULL || mg->mg_class != mc)
1006 			continue;
1007 
1008 		metaslab_group_histogram_verify(mg);
1009 		mg->mg_fragmentation = metaslab_group_fragmentation(mg);
1010 
1011 		(void) printf("\tvdev %10llu\t\tmetaslabs%5llu\t\t"
1012 		    "fragmentation",
1013 		    (u_longlong_t)tvd->vdev_id,
1014 		    (u_longlong_t)tvd->vdev_ms_count);
1015 		if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
1016 			(void) printf("%3s\n", "-");
1017 		} else {
1018 			(void) printf("%3llu%%\n",
1019 			    (u_longlong_t)mg->mg_fragmentation);
1020 		}
1021 		dump_histogram(mg->mg_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1022 	}
1023 
1024 	(void) printf("\tpool %s\tfragmentation", spa_name(spa));
1025 	fragmentation = metaslab_class_fragmentation(mc);
1026 	if (fragmentation == ZFS_FRAG_INVALID)
1027 		(void) printf("\t%3s\n", "-");
1028 	else
1029 		(void) printf("\t%3llu%%\n", (u_longlong_t)fragmentation);
1030 	dump_histogram(mc->mc_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
1031 }
1032 
1033 static void
1034 print_vdev_indirect(vdev_t *vd)
1035 {
1036 	vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
1037 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
1038 	vdev_indirect_births_t *vib = vd->vdev_indirect_births;
1039 
1040 	if (vim == NULL) {
1041 		ASSERT3P(vib, ==, NULL);
1042 		return;
1043 	}
1044 
1045 	ASSERT3U(vdev_indirect_mapping_object(vim), ==,
1046 	    vic->vic_mapping_object);
1047 	ASSERT3U(vdev_indirect_births_object(vib), ==,
1048 	    vic->vic_births_object);
1049 
1050 	(void) printf("indirect births obj %llu:\n",
1051 	    (longlong_t)vic->vic_births_object);
1052 	(void) printf("    vib_count = %llu\n",
1053 	    (longlong_t)vdev_indirect_births_count(vib));
1054 	for (uint64_t i = 0; i < vdev_indirect_births_count(vib); i++) {
1055 		vdev_indirect_birth_entry_phys_t *cur_vibe =
1056 		    &vib->vib_entries[i];
1057 		(void) printf("\toffset %llx -> txg %llu\n",
1058 		    (longlong_t)cur_vibe->vibe_offset,
1059 		    (longlong_t)cur_vibe->vibe_phys_birth_txg);
1060 	}
1061 	(void) printf("\n");
1062 
1063 	(void) printf("indirect mapping obj %llu:\n",
1064 	    (longlong_t)vic->vic_mapping_object);
1065 	(void) printf("    vim_max_offset = 0x%llx\n",
1066 	    (longlong_t)vdev_indirect_mapping_max_offset(vim));
1067 	(void) printf("    vim_bytes_mapped = 0x%llx\n",
1068 	    (longlong_t)vdev_indirect_mapping_bytes_mapped(vim));
1069 	(void) printf("    vim_count = %llu\n",
1070 	    (longlong_t)vdev_indirect_mapping_num_entries(vim));
1071 
1072 	if (dump_opt['d'] <= 5 && dump_opt['m'] <= 3)
1073 		return;
1074 
1075 	uint32_t *counts = vdev_indirect_mapping_load_obsolete_counts(vim);
1076 
1077 	for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
1078 		vdev_indirect_mapping_entry_phys_t *vimep =
1079 		    &vim->vim_entries[i];
1080 		(void) printf("\t<%llx:%llx:%llx> -> "
1081 		    "<%llx:%llx:%llx> (%x obsolete)\n",
1082 		    (longlong_t)vd->vdev_id,
1083 		    (longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
1084 		    (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1085 		    (longlong_t)DVA_GET_VDEV(&vimep->vimep_dst),
1086 		    (longlong_t)DVA_GET_OFFSET(&vimep->vimep_dst),
1087 		    (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
1088 		    counts[i]);
1089 	}
1090 	(void) printf("\n");
1091 
1092 	uint64_t obsolete_sm_object = vdev_obsolete_sm_object(vd);
1093 	if (obsolete_sm_object != 0) {
1094 		objset_t *mos = vd->vdev_spa->spa_meta_objset;
1095 		(void) printf("obsolete space map object %llu:\n",
1096 		    (u_longlong_t)obsolete_sm_object);
1097 		ASSERT(vd->vdev_obsolete_sm != NULL);
1098 		ASSERT3U(space_map_object(vd->vdev_obsolete_sm), ==,
1099 		    obsolete_sm_object);
1100 		dump_spacemap(mos, vd->vdev_obsolete_sm);
1101 		(void) printf("\n");
1102 	}
1103 }
1104 
1105 static void
1106 dump_metaslabs(spa_t *spa)
1107 {
1108 	vdev_t *vd, *rvd = spa->spa_root_vdev;
1109 	uint64_t m, c = 0, children = rvd->vdev_children;
1110 
1111 	(void) printf("\nMetaslabs:\n");
1112 
1113 	if (!dump_opt['d'] && zopt_objects > 0) {
1114 		c = zopt_object[0];
1115 
1116 		if (c >= children)
1117 			(void) fatal("bad vdev id: %llu", (u_longlong_t)c);
1118 
1119 		if (zopt_objects > 1) {
1120 			vd = rvd->vdev_child[c];
1121 			print_vdev_metaslab_header(vd);
1122 
1123 			for (m = 1; m < zopt_objects; m++) {
1124 				if (zopt_object[m] < vd->vdev_ms_count)
1125 					dump_metaslab(
1126 					    vd->vdev_ms[zopt_object[m]]);
1127 				else
1128 					(void) fprintf(stderr, "bad metaslab "
1129 					    "number %llu\n",
1130 					    (u_longlong_t)zopt_object[m]);
1131 			}
1132 			(void) printf("\n");
1133 			return;
1134 		}
1135 		children = c + 1;
1136 	}
1137 	for (; c < children; c++) {
1138 		vd = rvd->vdev_child[c];
1139 		print_vdev_metaslab_header(vd);
1140 
1141 		print_vdev_indirect(vd);
1142 
1143 		for (m = 0; m < vd->vdev_ms_count; m++)
1144 			dump_metaslab(vd->vdev_ms[m]);
1145 		(void) printf("\n");
1146 	}
1147 }
1148 
1149 static void
1150 dump_log_spacemaps(spa_t *spa)
1151 {
1152 	if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
1153 		return;
1154 
1155 	(void) printf("\nLog Space Maps in Pool:\n");
1156 	for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
1157 	    sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls)) {
1158 		space_map_t *sm = NULL;
1159 		VERIFY0(space_map_open(&sm, spa_meta_objset(spa),
1160 		    sls->sls_sm_obj, 0, UINT64_MAX, SPA_MINBLOCKSHIFT));
1161 
1162 		(void) printf("Log Spacemap object %llu txg %llu\n",
1163 		    (u_longlong_t)sls->sls_sm_obj, (u_longlong_t)sls->sls_txg);
1164 		dump_spacemap(spa->spa_meta_objset, sm);
1165 		space_map_close(sm);
1166 	}
1167 	(void) printf("\n");
1168 }
1169 
1170 static void
1171 dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
1172 {
1173 	const ddt_phys_t *ddp = dde->dde_phys;
1174 	const ddt_key_t *ddk = &dde->dde_key;
1175 	const char *types[4] = { "ditto", "single", "double", "triple" };
1176 	char blkbuf[BP_SPRINTF_LEN];
1177 	blkptr_t blk;
1178 
1179 	for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1180 		if (ddp->ddp_phys_birth == 0)
1181 			continue;
1182 		ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
1183 		snprintf_blkptr(blkbuf, sizeof (blkbuf), &blk);
1184 		(void) printf("index %llx refcnt %llu %s %s\n",
1185 		    (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
1186 		    types[p], blkbuf);
1187 	}
1188 }
1189 
1190 static void
1191 dump_dedup_ratio(const ddt_stat_t *dds)
1192 {
1193 	double rL, rP, rD, D, dedup, compress, copies;
1194 
1195 	if (dds->dds_blocks == 0)
1196 		return;
1197 
1198 	rL = (double)dds->dds_ref_lsize;
1199 	rP = (double)dds->dds_ref_psize;
1200 	rD = (double)dds->dds_ref_dsize;
1201 	D = (double)dds->dds_dsize;
1202 
1203 	dedup = rD / D;
1204 	compress = rL / rP;
1205 	copies = rD / rP;
1206 
1207 	(void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
1208 	    "dedup * compress / copies = %.2f\n\n",
1209 	    dedup, compress, copies, dedup * compress / copies);
1210 }
1211 
1212 static void
1213 dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
1214 {
1215 	char name[DDT_NAMELEN];
1216 	ddt_entry_t dde;
1217 	uint64_t walk = 0;
1218 	dmu_object_info_t doi;
1219 	uint64_t count, dspace, mspace;
1220 	int error;
1221 
1222 	error = ddt_object_info(ddt, type, class, &doi);
1223 
1224 	if (error == ENOENT)
1225 		return;
1226 	ASSERT(error == 0);
1227 
1228 	if ((count = ddt_object_count(ddt, type, class)) == 0)
1229 		return;
1230 
1231 	dspace = doi.doi_physical_blocks_512 << 9;
1232 	mspace = doi.doi_fill_count * doi.doi_data_block_size;
1233 
1234 	ddt_object_name(ddt, type, class, name);
1235 
1236 	(void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
1237 	    name,
1238 	    (u_longlong_t)count,
1239 	    (u_longlong_t)(dspace / count),
1240 	    (u_longlong_t)(mspace / count));
1241 
1242 	if (dump_opt['D'] < 3)
1243 		return;
1244 
1245 	zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
1246 
1247 	if (dump_opt['D'] < 4)
1248 		return;
1249 
1250 	if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
1251 		return;
1252 
1253 	(void) printf("%s contents:\n\n", name);
1254 
1255 	while ((error = ddt_object_walk(ddt, type, class, &walk, &dde)) == 0)
1256 		dump_dde(ddt, &dde, walk);
1257 
1258 	ASSERT3U(error, ==, ENOENT);
1259 
1260 	(void) printf("\n");
1261 }
1262 
1263 static void
1264 dump_all_ddts(spa_t *spa)
1265 {
1266 	ddt_histogram_t ddh_total;
1267 	ddt_stat_t dds_total;
1268 
1269 	bzero(&ddh_total, sizeof (ddh_total));
1270 	bzero(&dds_total, sizeof (dds_total));
1271 
1272 	for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1273 		ddt_t *ddt = spa->spa_ddt[c];
1274 		for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
1275 			for (enum ddt_class class = 0; class < DDT_CLASSES;
1276 			    class++) {
1277 				dump_ddt(ddt, type, class);
1278 			}
1279 		}
1280 	}
1281 
1282 	ddt_get_dedup_stats(spa, &dds_total);
1283 
1284 	if (dds_total.dds_blocks == 0) {
1285 		(void) printf("All DDTs are empty\n");
1286 		return;
1287 	}
1288 
1289 	(void) printf("\n");
1290 
1291 	if (dump_opt['D'] > 1) {
1292 		(void) printf("DDT histogram (aggregated over all DDTs):\n");
1293 		ddt_get_dedup_histogram(spa, &ddh_total);
1294 		zpool_dump_ddt(&dds_total, &ddh_total);
1295 	}
1296 
1297 	dump_dedup_ratio(&dds_total);
1298 }
1299 
1300 static void
1301 dump_dtl_seg(void *arg, uint64_t start, uint64_t size)
1302 {
1303 	char *prefix = arg;
1304 
1305 	(void) printf("%s [%llu,%llu) length %llu\n",
1306 	    prefix,
1307 	    (u_longlong_t)start,
1308 	    (u_longlong_t)(start + size),
1309 	    (u_longlong_t)(size));
1310 }
1311 
1312 static void
1313 dump_dtl(vdev_t *vd, int indent)
1314 {
1315 	spa_t *spa = vd->vdev_spa;
1316 	boolean_t required;
1317 	const char *name[DTL_TYPES] = { "missing", "partial", "scrub",
1318 		"outage" };
1319 	char prefix[256];
1320 
1321 	spa_vdev_state_enter(spa, SCL_NONE);
1322 	required = vdev_dtl_required(vd);
1323 	(void) spa_vdev_state_exit(spa, NULL, 0);
1324 
1325 	if (indent == 0)
1326 		(void) printf("\nDirty time logs:\n\n");
1327 
1328 	(void) printf("\t%*s%s [%s]\n", indent, "",
1329 	    vd->vdev_path ? vd->vdev_path :
1330 	    vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
1331 	    required ? "DTL-required" : "DTL-expendable");
1332 
1333 	for (int t = 0; t < DTL_TYPES; t++) {
1334 		range_tree_t *rt = vd->vdev_dtl[t];
1335 		if (range_tree_space(rt) == 0)
1336 			continue;
1337 		(void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
1338 		    indent + 2, "", name[t]);
1339 		range_tree_walk(rt, dump_dtl_seg, prefix);
1340 		if (dump_opt['d'] > 5 && vd->vdev_children == 0)
1341 			dump_spacemap(spa->spa_meta_objset, vd->vdev_dtl_sm);
1342 	}
1343 
1344 	for (unsigned c = 0; c < vd->vdev_children; c++)
1345 		dump_dtl(vd->vdev_child[c], indent + 4);
1346 }
1347 
1348 static void
1349 dump_history(spa_t *spa)
1350 {
1351 	nvlist_t **events = NULL;
1352 	uint64_t resid, len, off = 0;
1353 	uint_t num = 0;
1354 	int error;
1355 	time_t tsec;
1356 	struct tm t;
1357 	char tbuf[30];
1358 	char internalstr[MAXPATHLEN];
1359 
1360 	char *buf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
1361 	do {
1362 		len = SPA_MAXBLOCKSIZE;
1363 
1364 		if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
1365 			(void) fprintf(stderr, "Unable to read history: "
1366 			    "error %d\n", error);
1367 			umem_free(buf, SPA_MAXBLOCKSIZE);
1368 			return;
1369 		}
1370 
1371 		if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
1372 			break;
1373 
1374 		off -= resid;
1375 	} while (len != 0);
1376 	umem_free(buf, SPA_MAXBLOCKSIZE);
1377 
1378 	(void) printf("\nHistory:\n");
1379 	for (unsigned i = 0; i < num; i++) {
1380 		uint64_t time, txg, ievent;
1381 		char *cmd, *intstr;
1382 		boolean_t printed = B_FALSE;
1383 
1384 		if (nvlist_lookup_uint64(events[i], ZPOOL_HIST_TIME,
1385 		    &time) != 0)
1386 			goto next;
1387 		if (nvlist_lookup_string(events[i], ZPOOL_HIST_CMD,
1388 		    &cmd) != 0) {
1389 			if (nvlist_lookup_uint64(events[i],
1390 			    ZPOOL_HIST_INT_EVENT, &ievent) != 0)
1391 				goto next;
1392 			verify(nvlist_lookup_uint64(events[i],
1393 			    ZPOOL_HIST_TXG, &txg) == 0);
1394 			verify(nvlist_lookup_string(events[i],
1395 			    ZPOOL_HIST_INT_STR, &intstr) == 0);
1396 			if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
1397 				goto next;
1398 
1399 			(void) snprintf(internalstr,
1400 			    sizeof (internalstr),
1401 			    "[internal %s txg:%ju] %s",
1402 			    zfs_history_event_names[ievent], (uintmax_t)txg,
1403 			    intstr);
1404 			cmd = internalstr;
1405 		}
1406 		tsec = time;
1407 		(void) localtime_r(&tsec, &t);
1408 		(void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
1409 		(void) printf("%s %s\n", tbuf, cmd);
1410 		printed = B_TRUE;
1411 
1412 next:
1413 		if (dump_opt['h'] > 1) {
1414 			if (!printed)
1415 				(void) printf("unrecognized record:\n");
1416 			dump_nvlist(events[i], 2);
1417 		}
1418 	}
1419 }
1420 
1421 /*ARGSUSED*/
1422 static void
1423 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
1424 {
1425 }
1426 
1427 static uint64_t
1428 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp,
1429     const zbookmark_phys_t *zb)
1430 {
1431 	if (dnp == NULL) {
1432 		ASSERT(zb->zb_level < 0);
1433 		if (zb->zb_object == 0)
1434 			return (zb->zb_blkid);
1435 		return (zb->zb_blkid * BP_GET_LSIZE(bp));
1436 	}
1437 
1438 	ASSERT(zb->zb_level >= 0);
1439 
1440 	return ((zb->zb_blkid <<
1441 	    (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
1442 	    dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
1443 }
1444 
1445 static void
1446 snprintf_blkptr_compact(char *blkbuf, size_t buflen, const blkptr_t *bp)
1447 {
1448 	const dva_t *dva = bp->blk_dva;
1449 	unsigned int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
1450 
1451 	if (dump_opt['b'] >= 6) {
1452 		snprintf_blkptr(blkbuf, buflen, bp);
1453 		return;
1454 	}
1455 
1456 	if (BP_IS_EMBEDDED(bp)) {
1457 		(void) sprintf(blkbuf,
1458 		    "EMBEDDED et=%u %llxL/%llxP B=%llu",
1459 		    (int)BPE_GET_ETYPE(bp),
1460 		    (u_longlong_t)BPE_GET_LSIZE(bp),
1461 		    (u_longlong_t)BPE_GET_PSIZE(bp),
1462 		    (u_longlong_t)bp->blk_birth);
1463 		return;
1464 	}
1465 
1466 	blkbuf[0] = '\0';
1467 	for (unsigned int i = 0; i < ndvas; i++)
1468 		(void) snprintf(blkbuf + strlen(blkbuf),
1469 		    buflen - strlen(blkbuf), "%llu:%llx:%llx ",
1470 		    (u_longlong_t)DVA_GET_VDEV(&dva[i]),
1471 		    (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
1472 		    (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
1473 
1474 	if (BP_IS_HOLE(bp)) {
1475 		(void) snprintf(blkbuf + strlen(blkbuf),
1476 		    buflen - strlen(blkbuf),
1477 		    "%llxL B=%llu",
1478 		    (u_longlong_t)BP_GET_LSIZE(bp),
1479 		    (u_longlong_t)bp->blk_birth);
1480 	} else {
1481 		(void) snprintf(blkbuf + strlen(blkbuf),
1482 		    buflen - strlen(blkbuf),
1483 		    "%llxL/%llxP F=%llu B=%llu/%llu",
1484 		    (u_longlong_t)BP_GET_LSIZE(bp),
1485 		    (u_longlong_t)BP_GET_PSIZE(bp),
1486 		    (u_longlong_t)BP_GET_FILL(bp),
1487 		    (u_longlong_t)bp->blk_birth,
1488 		    (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
1489 	}
1490 }
1491 
1492 static void
1493 print_indirect(blkptr_t *bp, const zbookmark_phys_t *zb,
1494     const dnode_phys_t *dnp)
1495 {
1496 	char blkbuf[BP_SPRINTF_LEN];
1497 	int l;
1498 
1499 	if (!BP_IS_EMBEDDED(bp)) {
1500 		ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
1501 		ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
1502 	}
1503 
1504 	(void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
1505 
1506 	ASSERT(zb->zb_level >= 0);
1507 
1508 	for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
1509 		if (l == zb->zb_level) {
1510 			(void) printf("L%llx", (u_longlong_t)zb->zb_level);
1511 		} else {
1512 			(void) printf(" ");
1513 		}
1514 	}
1515 
1516 	snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1517 	(void) printf("%s\n", blkbuf);
1518 }
1519 
1520 static int
1521 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
1522     blkptr_t *bp, const zbookmark_phys_t *zb)
1523 {
1524 	int err = 0;
1525 
1526 	if (bp->blk_birth == 0)
1527 		return (0);
1528 
1529 	print_indirect(bp, zb, dnp);
1530 
1531 	if (BP_GET_LEVEL(bp) > 0 && !BP_IS_HOLE(bp)) {
1532 		arc_flags_t flags = ARC_FLAG_WAIT;
1533 		int i;
1534 		blkptr_t *cbp;
1535 		int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
1536 		arc_buf_t *buf;
1537 		uint64_t fill = 0;
1538 
1539 		err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
1540 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
1541 		if (err)
1542 			return (err);
1543 		ASSERT(buf->b_data);
1544 
1545 		/* recursively visit blocks below this */
1546 		cbp = buf->b_data;
1547 		for (i = 0; i < epb; i++, cbp++) {
1548 			zbookmark_phys_t czb;
1549 
1550 			SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1551 			    zb->zb_level - 1,
1552 			    zb->zb_blkid * epb + i);
1553 			err = visit_indirect(spa, dnp, cbp, &czb);
1554 			if (err)
1555 				break;
1556 			fill += BP_GET_FILL(cbp);
1557 		}
1558 		if (!err)
1559 			ASSERT3U(fill, ==, BP_GET_FILL(bp));
1560 		arc_buf_destroy(buf, &buf);
1561 	}
1562 
1563 	return (err);
1564 }
1565 
1566 /*ARGSUSED*/
1567 static void
1568 dump_indirect(dnode_t *dn)
1569 {
1570 	dnode_phys_t *dnp = dn->dn_phys;
1571 	int j;
1572 	zbookmark_phys_t czb;
1573 
1574 	(void) printf("Indirect blocks:\n");
1575 
1576 	SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
1577 	    dn->dn_object, dnp->dn_nlevels - 1, 0);
1578 	for (j = 0; j < dnp->dn_nblkptr; j++) {
1579 		czb.zb_blkid = j;
1580 		(void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
1581 		    &dnp->dn_blkptr[j], &czb);
1582 	}
1583 
1584 	(void) printf("\n");
1585 }
1586 
1587 /*ARGSUSED*/
1588 static void
1589 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
1590 {
1591 	dsl_dir_phys_t *dd = data;
1592 	time_t crtime;
1593 	char nice[32];
1594 
1595 	/* make sure nicenum has enough space */
1596 	CTASSERT(sizeof (nice) >= NN_NUMBUF_SZ);
1597 
1598 	if (dd == NULL)
1599 		return;
1600 
1601 	ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
1602 
1603 	crtime = dd->dd_creation_time;
1604 	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
1605 	(void) printf("\t\thead_dataset_obj = %llu\n",
1606 	    (u_longlong_t)dd->dd_head_dataset_obj);
1607 	(void) printf("\t\tparent_dir_obj = %llu\n",
1608 	    (u_longlong_t)dd->dd_parent_obj);
1609 	(void) printf("\t\torigin_obj = %llu\n",
1610 	    (u_longlong_t)dd->dd_origin_obj);
1611 	(void) printf("\t\tchild_dir_zapobj = %llu\n",
1612 	    (u_longlong_t)dd->dd_child_dir_zapobj);
1613 	zdb_nicenum(dd->dd_used_bytes, nice, sizeof (nice));
1614 	(void) printf("\t\tused_bytes = %s\n", nice);
1615 	zdb_nicenum(dd->dd_compressed_bytes, nice, sizeof (nice));
1616 	(void) printf("\t\tcompressed_bytes = %s\n", nice);
1617 	zdb_nicenum(dd->dd_uncompressed_bytes, nice, sizeof (nice));
1618 	(void) printf("\t\tuncompressed_bytes = %s\n", nice);
1619 	zdb_nicenum(dd->dd_quota, nice, sizeof (nice));
1620 	(void) printf("\t\tquota = %s\n", nice);
1621 	zdb_nicenum(dd->dd_reserved, nice, sizeof (nice));
1622 	(void) printf("\t\treserved = %s\n", nice);
1623 	(void) printf("\t\tprops_zapobj = %llu\n",
1624 	    (u_longlong_t)dd->dd_props_zapobj);
1625 	(void) printf("\t\tdeleg_zapobj = %llu\n",
1626 	    (u_longlong_t)dd->dd_deleg_zapobj);
1627 	(void) printf("\t\tflags = %llx\n",
1628 	    (u_longlong_t)dd->dd_flags);
1629 
1630 #define	DO(which) \
1631 	zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice, \
1632 	    sizeof (nice)); \
1633 	(void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
1634 	DO(HEAD);
1635 	DO(SNAP);
1636 	DO(CHILD);
1637 	DO(CHILD_RSRV);
1638 	DO(REFRSRV);
1639 #undef DO
1640 	(void) printf("\t\tclones = %llu\n",
1641 	    (u_longlong_t)dd->dd_clones);
1642 }
1643 
1644 /*ARGSUSED*/
1645 static void
1646 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
1647 {
1648 	dsl_dataset_phys_t *ds = data;
1649 	time_t crtime;
1650 	char used[32], compressed[32], uncompressed[32], unique[32];
1651 	char blkbuf[BP_SPRINTF_LEN];
1652 
1653 	/* make sure nicenum has enough space */
1654 	CTASSERT(sizeof (used) >= NN_NUMBUF_SZ);
1655 	CTASSERT(sizeof (compressed) >= NN_NUMBUF_SZ);
1656 	CTASSERT(sizeof (uncompressed) >= NN_NUMBUF_SZ);
1657 	CTASSERT(sizeof (unique) >= NN_NUMBUF_SZ);
1658 
1659 	if (ds == NULL)
1660 		return;
1661 
1662 	ASSERT(size == sizeof (*ds));
1663 	crtime = ds->ds_creation_time;
1664 	zdb_nicenum(ds->ds_referenced_bytes, used, sizeof (used));
1665 	zdb_nicenum(ds->ds_compressed_bytes, compressed, sizeof (compressed));
1666 	zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed,
1667 	    sizeof (uncompressed));
1668 	zdb_nicenum(ds->ds_unique_bytes, unique, sizeof (unique));
1669 	snprintf_blkptr(blkbuf, sizeof (blkbuf), &ds->ds_bp);
1670 
1671 	(void) printf("\t\tdir_obj = %llu\n",
1672 	    (u_longlong_t)ds->ds_dir_obj);
1673 	(void) printf("\t\tprev_snap_obj = %llu\n",
1674 	    (u_longlong_t)ds->ds_prev_snap_obj);
1675 	(void) printf("\t\tprev_snap_txg = %llu\n",
1676 	    (u_longlong_t)ds->ds_prev_snap_txg);
1677 	(void) printf("\t\tnext_snap_obj = %llu\n",
1678 	    (u_longlong_t)ds->ds_next_snap_obj);
1679 	(void) printf("\t\tsnapnames_zapobj = %llu\n",
1680 	    (u_longlong_t)ds->ds_snapnames_zapobj);
1681 	(void) printf("\t\tnum_children = %llu\n",
1682 	    (u_longlong_t)ds->ds_num_children);
1683 	(void) printf("\t\tuserrefs_obj = %llu\n",
1684 	    (u_longlong_t)ds->ds_userrefs_obj);
1685 	(void) printf("\t\tcreation_time = %s", ctime(&crtime));
1686 	(void) printf("\t\tcreation_txg = %llu\n",
1687 	    (u_longlong_t)ds->ds_creation_txg);
1688 	(void) printf("\t\tdeadlist_obj = %llu\n",
1689 	    (u_longlong_t)ds->ds_deadlist_obj);
1690 	(void) printf("\t\tused_bytes = %s\n", used);
1691 	(void) printf("\t\tcompressed_bytes = %s\n", compressed);
1692 	(void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
1693 	(void) printf("\t\tunique = %s\n", unique);
1694 	(void) printf("\t\tfsid_guid = %llu\n",
1695 	    (u_longlong_t)ds->ds_fsid_guid);
1696 	(void) printf("\t\tguid = %llu\n",
1697 	    (u_longlong_t)ds->ds_guid);
1698 	(void) printf("\t\tflags = %llx\n",
1699 	    (u_longlong_t)ds->ds_flags);
1700 	(void) printf("\t\tnext_clones_obj = %llu\n",
1701 	    (u_longlong_t)ds->ds_next_clones_obj);
1702 	(void) printf("\t\tprops_obj = %llu\n",
1703 	    (u_longlong_t)ds->ds_props_obj);
1704 	(void) printf("\t\tbp = %s\n", blkbuf);
1705 }
1706 
1707 /* ARGSUSED */
1708 static int
1709 dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1710 {
1711 	char blkbuf[BP_SPRINTF_LEN];
1712 
1713 	if (bp->blk_birth != 0) {
1714 		snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
1715 		(void) printf("\t%s\n", blkbuf);
1716 	}
1717 	return (0);
1718 }
1719 
1720 static void
1721 dump_bptree(objset_t *os, uint64_t obj, const char *name)
1722 {
1723 	char bytes[32];
1724 	bptree_phys_t *bt;
1725 	dmu_buf_t *db;
1726 
1727 	/* make sure nicenum has enough space */
1728 	CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1729 
1730 	if (dump_opt['d'] < 3)
1731 		return;
1732 
1733 	VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
1734 	bt = db->db_data;
1735 	zdb_nicenum(bt->bt_bytes, bytes, sizeof (bytes));
1736 	(void) printf("\n    %s: %llu datasets, %s\n",
1737 	    name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
1738 	dmu_buf_rele(db, FTAG);
1739 
1740 	if (dump_opt['d'] < 5)
1741 		return;
1742 
1743 	(void) printf("\n");
1744 
1745 	(void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
1746 }
1747 
1748 /* ARGSUSED */
1749 static int
1750 dump_bpobj_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1751 {
1752 	char blkbuf[BP_SPRINTF_LEN];
1753 
1754 	ASSERT(bp->blk_birth != 0);
1755 	snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1756 	(void) printf("\t%s\n", blkbuf);
1757 	return (0);
1758 }
1759 
1760 static void
1761 dump_full_bpobj(bpobj_t *bpo, const char *name, int indent)
1762 {
1763 	char bytes[32];
1764 	char comp[32];
1765 	char uncomp[32];
1766 
1767 	/* make sure nicenum has enough space */
1768 	CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1769 	CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1770 	CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1771 
1772 	if (dump_opt['d'] < 3)
1773 		return;
1774 
1775 	zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes, sizeof (bytes));
1776 	if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1777 		zdb_nicenum(bpo->bpo_phys->bpo_comp, comp, sizeof (comp));
1778 		zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp, sizeof (uncomp));
1779 		(void) printf("    %*s: object %llu, %llu local blkptrs, "
1780 		    "%llu subobjs in object %llu, %s (%s/%s comp)\n",
1781 		    indent * 8, name,
1782 		    (u_longlong_t)bpo->bpo_object,
1783 		    (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1784 		    (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
1785 		    (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
1786 		    bytes, comp, uncomp);
1787 
1788 		for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1789 			uint64_t subobj;
1790 			bpobj_t subbpo;
1791 			int error;
1792 			VERIFY0(dmu_read(bpo->bpo_os,
1793 			    bpo->bpo_phys->bpo_subobjs,
1794 			    i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1795 			error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1796 			if (error != 0) {
1797 				(void) printf("ERROR %u while trying to open "
1798 				    "subobj id %llu\n",
1799 				    error, (u_longlong_t)subobj);
1800 				continue;
1801 			}
1802 			dump_full_bpobj(&subbpo, "subobj", indent + 1);
1803 			bpobj_close(&subbpo);
1804 		}
1805 	} else {
1806 		(void) printf("    %*s: object %llu, %llu blkptrs, %s\n",
1807 		    indent * 8, name,
1808 		    (u_longlong_t)bpo->bpo_object,
1809 		    (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1810 		    bytes);
1811 	}
1812 
1813 	if (dump_opt['d'] < 5)
1814 		return;
1815 
1816 
1817 	if (indent == 0) {
1818 		(void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
1819 		(void) printf("\n");
1820 	}
1821 }
1822 
1823 static void
1824 bpobj_count_refd(bpobj_t *bpo)
1825 {
1826 	mos_obj_refd(bpo->bpo_object);
1827 
1828 	if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1829 		mos_obj_refd(bpo->bpo_phys->bpo_subobjs);
1830 		for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1831 			uint64_t subobj;
1832 			bpobj_t subbpo;
1833 			int error;
1834 			VERIFY0(dmu_read(bpo->bpo_os,
1835 			    bpo->bpo_phys->bpo_subobjs,
1836 			    i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1837 			error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1838 			if (error != 0) {
1839 				(void) printf("ERROR %u while trying to open "
1840 				    "subobj id %llu\n",
1841 				    error, (u_longlong_t)subobj);
1842 				continue;
1843 			}
1844 			bpobj_count_refd(&subbpo);
1845 			bpobj_close(&subbpo);
1846 		}
1847 	}
1848 }
1849 
1850 static void
1851 dump_deadlist(dsl_deadlist_t *dl)
1852 {
1853 	dsl_deadlist_entry_t *dle;
1854 	uint64_t unused;
1855 	char bytes[32];
1856 	char comp[32];
1857 	char uncomp[32];
1858 	uint64_t empty_bpobj =
1859 	    dmu_objset_spa(dl->dl_os)->spa_dsl_pool->dp_empty_bpobj;
1860 
1861 	/* force the tree to be loaded */
1862 	dsl_deadlist_space_range(dl, 0, UINT64_MAX, &unused, &unused, &unused);
1863 
1864 	if (dl->dl_oldfmt) {
1865 		if (dl->dl_bpobj.bpo_object != empty_bpobj)
1866 			bpobj_count_refd(&dl->dl_bpobj);
1867 	} else {
1868 		mos_obj_refd(dl->dl_object);
1869 		for (dle = avl_first(&dl->dl_tree); dle;
1870 		    dle = AVL_NEXT(&dl->dl_tree, dle)) {
1871 			if (dle->dle_bpobj.bpo_object != empty_bpobj)
1872 				bpobj_count_refd(&dle->dle_bpobj);
1873 		}
1874 	}
1875 
1876 	/* make sure nicenum has enough space */
1877 	CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1878 	CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1879 	CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1880 
1881 	if (dump_opt['d'] < 3)
1882 		return;
1883 
1884 	if (dl->dl_oldfmt) {
1885 		dump_full_bpobj(&dl->dl_bpobj, "old-format deadlist", 0);
1886 		return;
1887 	}
1888 
1889 	zdb_nicenum(dl->dl_phys->dl_used, bytes, sizeof (bytes));
1890 	zdb_nicenum(dl->dl_phys->dl_comp, comp, sizeof (comp));
1891 	zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp, sizeof (uncomp));
1892 	(void) printf("\n    Deadlist: %s (%s/%s comp)\n",
1893 	    bytes, comp, uncomp);
1894 
1895 	if (dump_opt['d'] < 4)
1896 		return;
1897 
1898 	(void) printf("\n");
1899 
1900 	for (dle = avl_first(&dl->dl_tree); dle;
1901 	    dle = AVL_NEXT(&dl->dl_tree, dle)) {
1902 		if (dump_opt['d'] >= 5) {
1903 			char buf[128];
1904 			(void) snprintf(buf, sizeof (buf),
1905 			    "mintxg %llu -> obj %llu",
1906 			    (longlong_t)dle->dle_mintxg,
1907 			    (longlong_t)dle->dle_bpobj.bpo_object);
1908 
1909 			dump_full_bpobj(&dle->dle_bpobj, buf, 0);
1910 		} else {
1911 			(void) printf("mintxg %llu -> obj %llu\n",
1912 			    (longlong_t)dle->dle_mintxg,
1913 			    (longlong_t)dle->dle_bpobj.bpo_object);
1914 		}
1915 	}
1916 }
1917 
1918 static avl_tree_t idx_tree;
1919 static avl_tree_t domain_tree;
1920 static boolean_t fuid_table_loaded;
1921 static objset_t *sa_os = NULL;
1922 static sa_attr_type_t *sa_attr_table = NULL;
1923 
1924 static int
1925 open_objset(const char *path, dmu_objset_type_t type, void *tag, objset_t **osp)
1926 {
1927 	int err;
1928 	uint64_t sa_attrs = 0;
1929 	uint64_t version = 0;
1930 
1931 	VERIFY3P(sa_os, ==, NULL);
1932 	err = dmu_objset_own(path, type, B_TRUE, B_FALSE, tag, osp);
1933 	if (err != 0) {
1934 		(void) fprintf(stderr, "failed to own dataset '%s': %s\n", path,
1935 		    strerror(err));
1936 		return (err);
1937 	}
1938 
1939 	if (dmu_objset_type(*osp) == DMU_OST_ZFS && !(*osp)->os_encrypted) {
1940 		(void) zap_lookup(*osp, MASTER_NODE_OBJ, ZPL_VERSION_STR,
1941 		    8, 1, &version);
1942 		if (version >= ZPL_VERSION_SA) {
1943 			(void) zap_lookup(*osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
1944 			    8, 1, &sa_attrs);
1945 		}
1946 		err = sa_setup(*osp, sa_attrs, zfs_attr_table, ZPL_END,
1947 		    &sa_attr_table);
1948 		if (err != 0) {
1949 			(void) fprintf(stderr, "sa_setup failed: %s\n",
1950 			    strerror(err));
1951 			dmu_objset_disown(*osp, B_FALSE, tag);
1952 			*osp = NULL;
1953 		}
1954 	}
1955 	sa_os = *osp;
1956 
1957 	return (0);
1958 }
1959 
1960 static void
1961 close_objset(objset_t *os, void *tag)
1962 {
1963 	VERIFY3P(os, ==, sa_os);
1964 	if (os->os_sa != NULL)
1965 		sa_tear_down(os);
1966 	dmu_objset_disown(os, B_FALSE, tag);
1967 	sa_attr_table = NULL;
1968 	sa_os = NULL;
1969 }
1970 
1971 static void
1972 fuid_table_destroy()
1973 {
1974 	if (fuid_table_loaded) {
1975 		zfs_fuid_table_destroy(&idx_tree, &domain_tree);
1976 		fuid_table_loaded = B_FALSE;
1977 	}
1978 }
1979 
1980 /*
1981  * print uid or gid information.
1982  * For normal POSIX id just the id is printed in decimal format.
1983  * For CIFS files with FUID the fuid is printed in hex followed by
1984  * the domain-rid string.
1985  */
1986 static void
1987 print_idstr(uint64_t id, const char *id_type)
1988 {
1989 	if (FUID_INDEX(id)) {
1990 		char *domain;
1991 
1992 		domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
1993 		(void) printf("\t%s     %llx [%s-%d]\n", id_type,
1994 		    (u_longlong_t)id, domain, (int)FUID_RID(id));
1995 	} else {
1996 		(void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
1997 	}
1998 
1999 }
2000 
2001 static void
2002 dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
2003 {
2004 	uint32_t uid_idx, gid_idx;
2005 
2006 	uid_idx = FUID_INDEX(uid);
2007 	gid_idx = FUID_INDEX(gid);
2008 
2009 	/* Load domain table, if not already loaded */
2010 	if (!fuid_table_loaded && (uid_idx || gid_idx)) {
2011 		uint64_t fuid_obj;
2012 
2013 		/* first find the fuid object.  It lives in the master node */
2014 		VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
2015 		    8, 1, &fuid_obj) == 0);
2016 		zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
2017 		(void) zfs_fuid_table_load(os, fuid_obj,
2018 		    &idx_tree, &domain_tree);
2019 		fuid_table_loaded = B_TRUE;
2020 	}
2021 
2022 	print_idstr(uid, "uid");
2023 	print_idstr(gid, "gid");
2024 }
2025 
2026 /*ARGSUSED*/
2027 static void
2028 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
2029 {
2030 	char path[MAXPATHLEN * 2];	/* allow for xattr and failure prefix */
2031 	sa_handle_t *hdl;
2032 	uint64_t xattr, rdev, gen;
2033 	uint64_t uid, gid, mode, fsize, parent, links;
2034 	uint64_t pflags;
2035 	uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
2036 	time_t z_crtime, z_atime, z_mtime, z_ctime;
2037 	sa_bulk_attr_t bulk[12];
2038 	int idx = 0;
2039 	int error;
2040 
2041 	VERIFY3P(os, ==, sa_os);
2042 	if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
2043 		(void) printf("Failed to get handle for SA znode\n");
2044 		return;
2045 	}
2046 
2047 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
2048 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
2049 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
2050 	    &links, 8);
2051 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
2052 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
2053 	    &mode, 8);
2054 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
2055 	    NULL, &parent, 8);
2056 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
2057 	    &fsize, 8);
2058 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
2059 	    acctm, 16);
2060 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
2061 	    modtm, 16);
2062 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
2063 	    crtm, 16);
2064 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
2065 	    chgtm, 16);
2066 	SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
2067 	    &pflags, 8);
2068 
2069 	if (sa_bulk_lookup(hdl, bulk, idx)) {
2070 		(void) sa_handle_destroy(hdl);
2071 		return;
2072 	}
2073 
2074 	z_crtime = (time_t)crtm[0];
2075 	z_atime = (time_t)acctm[0];
2076 	z_mtime = (time_t)modtm[0];
2077 	z_ctime = (time_t)chgtm[0];
2078 
2079 	if (dump_opt['d'] > 4) {
2080 		error = zfs_obj_to_path(os, object, path, sizeof (path));
2081 		if (error == ESTALE) {
2082 			(void) snprintf(path, sizeof (path), "on delete queue");
2083 		} else if (error != 0) {
2084 			leaked_objects++;
2085 			(void) snprintf(path, sizeof (path),
2086 			    "path not found, possibly leaked");
2087 		}
2088 		(void) printf("\tpath	%s\n", path);
2089 	}
2090 	dump_uidgid(os, uid, gid);
2091 	(void) printf("\tatime	%s", ctime(&z_atime));
2092 	(void) printf("\tmtime	%s", ctime(&z_mtime));
2093 	(void) printf("\tctime	%s", ctime(&z_ctime));
2094 	(void) printf("\tcrtime	%s", ctime(&z_crtime));
2095 	(void) printf("\tgen	%llu\n", (u_longlong_t)gen);
2096 	(void) printf("\tmode	%llo\n", (u_longlong_t)mode);
2097 	(void) printf("\tsize	%llu\n", (u_longlong_t)fsize);
2098 	(void) printf("\tparent	%llu\n", (u_longlong_t)parent);
2099 	(void) printf("\tlinks	%llu\n", (u_longlong_t)links);
2100 	(void) printf("\tpflags	%llx\n", (u_longlong_t)pflags);
2101 	if (dmu_objset_projectquota_enabled(os) && (pflags & ZFS_PROJID)) {
2102 		uint64_t projid;
2103 
2104 		if (sa_lookup(hdl, sa_attr_table[ZPL_PROJID], &projid,
2105 		    sizeof (uint64_t)) == 0)
2106 			(void) printf("\tprojid	%llu\n", (u_longlong_t)projid);
2107 	}
2108 	if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
2109 	    sizeof (uint64_t)) == 0)
2110 		(void) printf("\txattr	%llu\n", (u_longlong_t)xattr);
2111 	if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
2112 	    sizeof (uint64_t)) == 0)
2113 		(void) printf("\trdev	0x%016llx\n", (u_longlong_t)rdev);
2114 	sa_handle_destroy(hdl);
2115 }
2116 
2117 /*ARGSUSED*/
2118 static void
2119 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
2120 {
2121 }
2122 
2123 /*ARGSUSED*/
2124 static void
2125 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
2126 {
2127 }
2128 
2129 
2130 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
2131 	dump_none,		/* unallocated			*/
2132 	dump_zap,		/* object directory		*/
2133 	dump_uint64,		/* object array			*/
2134 	dump_none,		/* packed nvlist		*/
2135 	dump_packed_nvlist,	/* packed nvlist size		*/
2136 	dump_none,		/* bpobj			*/
2137 	dump_bpobj,		/* bpobj header			*/
2138 	dump_none,		/* SPA space map header		*/
2139 	dump_none,		/* SPA space map		*/
2140 	dump_none,		/* ZIL intent log		*/
2141 	dump_dnode,		/* DMU dnode			*/
2142 	dump_dmu_objset,	/* DMU objset			*/
2143 	dump_dsl_dir,		/* DSL directory		*/
2144 	dump_zap,		/* DSL directory child map	*/
2145 	dump_zap,		/* DSL dataset snap map		*/
2146 	dump_zap,		/* DSL props			*/
2147 	dump_dsl_dataset,	/* DSL dataset			*/
2148 	dump_znode,		/* ZFS znode			*/
2149 	dump_acl,		/* ZFS V0 ACL			*/
2150 	dump_uint8,		/* ZFS plain file		*/
2151 	dump_zpldir,		/* ZFS directory		*/
2152 	dump_zap,		/* ZFS master node		*/
2153 	dump_zap,		/* ZFS delete queue		*/
2154 	dump_uint8,		/* zvol object			*/
2155 	dump_zap,		/* zvol prop			*/
2156 	dump_uint8,		/* other uint8[]		*/
2157 	dump_uint64,		/* other uint64[]		*/
2158 	dump_zap,		/* other ZAP			*/
2159 	dump_zap,		/* persistent error log		*/
2160 	dump_uint8,		/* SPA history			*/
2161 	dump_history_offsets,	/* SPA history offsets		*/
2162 	dump_zap,		/* Pool properties		*/
2163 	dump_zap,		/* DSL permissions		*/
2164 	dump_acl,		/* ZFS ACL			*/
2165 	dump_uint8,		/* ZFS SYSACL			*/
2166 	dump_none,		/* FUID nvlist			*/
2167 	dump_packed_nvlist,	/* FUID nvlist size		*/
2168 	dump_zap,		/* DSL dataset next clones	*/
2169 	dump_zap,		/* DSL scrub queue		*/
2170 	dump_zap,		/* ZFS user/group/project used	*/
2171 	dump_zap,		/* ZFS user/group/project quota	*/
2172 	dump_zap,		/* snapshot refcount tags	*/
2173 	dump_ddt_zap,		/* DDT ZAP object		*/
2174 	dump_zap,		/* DDT statistics		*/
2175 	dump_znode,		/* SA object			*/
2176 	dump_zap,		/* SA Master Node		*/
2177 	dump_sa_attrs,		/* SA attribute registration	*/
2178 	dump_sa_layouts,	/* SA attribute layouts		*/
2179 	dump_zap,		/* DSL scrub translations	*/
2180 	dump_none,		/* fake dedup BP		*/
2181 	dump_zap,		/* deadlist			*/
2182 	dump_none,		/* deadlist hdr			*/
2183 	dump_zap,		/* dsl clones			*/
2184 	dump_bpobj_subobjs,	/* bpobj subobjs		*/
2185 	dump_unknown,		/* Unknown type, must be last	*/
2186 };
2187 
2188 static void
2189 dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header,
2190     uint64_t *dnode_slots_used)
2191 {
2192 	dmu_buf_t *db = NULL;
2193 	dmu_object_info_t doi;
2194 	dnode_t *dn;
2195 	boolean_t dnode_held = B_FALSE;
2196 	void *bonus = NULL;
2197 	size_t bsize = 0;
2198 	char iblk[32], dblk[32], lsize[32], asize[32], fill[32], dnsize[32];
2199 	char bonus_size[32];
2200 	char aux[50];
2201 	int error;
2202 
2203 	/* make sure nicenum has enough space */
2204 	CTASSERT(sizeof (iblk) >= NN_NUMBUF_SZ);
2205 	CTASSERT(sizeof (dblk) >= NN_NUMBUF_SZ);
2206 	CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
2207 	CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
2208 	CTASSERT(sizeof (bonus_size) >= NN_NUMBUF_SZ);
2209 
2210 	if (*print_header) {
2211 		(void) printf("\n%10s  %3s  %5s  %5s  %5s  %6s  %5s  %6s  %s\n",
2212 		    "Object", "lvl", "iblk", "dblk", "dsize", "dnsize",
2213 		    "lsize", "%full", "type");
2214 		*print_header = 0;
2215 	}
2216 
2217 	if (object == 0) {
2218 		dn = DMU_META_DNODE(os);
2219 		dmu_object_info_from_dnode(dn, &doi);
2220 	} else {
2221 		/*
2222 		 * Encrypted datasets will have sensitive bonus buffers
2223 		 * encrypted. Therefore we cannot hold the bonus buffer and
2224 		 * must hold the dnode itself instead.
2225 		 */
2226 		error = dmu_object_info(os, object, &doi);
2227 		if (error)
2228 			fatal("dmu_object_info() failed, errno %u", error);
2229 
2230 		if (os->os_encrypted &&
2231 		    DMU_OT_IS_ENCRYPTED(doi.doi_bonus_type)) {
2232 			error = dnode_hold(os, object, FTAG, &dn);
2233 			if (error)
2234 				fatal("dnode_hold() failed, errno %u", error);
2235 			dnode_held = B_TRUE;
2236 		} else {
2237 			error = dmu_bonus_hold(os, object, FTAG, &db);
2238 			if (error)
2239 				fatal("dmu_bonus_hold(%llu) failed, errno %u",
2240 				    object, error);
2241 			bonus = db->db_data;
2242 			bsize = db->db_size;
2243 			dn = DB_DNODE((dmu_buf_impl_t *)db);
2244 		}
2245 	}
2246 
2247 	if (dnode_slots_used != NULL)
2248 		*dnode_slots_used = doi.doi_dnodesize / DNODE_MIN_SIZE;
2249 
2250 	zdb_nicenum(doi.doi_metadata_block_size, iblk, sizeof (iblk));
2251 	zdb_nicenum(doi.doi_data_block_size, dblk, sizeof (dblk));
2252 	zdb_nicenum(doi.doi_max_offset, lsize, sizeof (lsize));
2253 	zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize, sizeof (asize));
2254 	zdb_nicenum(doi.doi_bonus_size, bonus_size, sizeof (bonus_size));
2255 	zdb_nicenum(doi.doi_dnodesize, dnsize, sizeof (dnsize));
2256 	(void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
2257 	    doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
2258 	    doi.doi_max_offset);
2259 
2260 	aux[0] = '\0';
2261 
2262 	if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
2263 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
2264 		    ZDB_CHECKSUM_NAME(doi.doi_checksum));
2265 	}
2266 
2267 	if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
2268 		(void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
2269 		    ZDB_COMPRESS_NAME(doi.doi_compress));
2270 	}
2271 
2272 	(void) printf("%10" PRIu64
2273 	    "  %3u  %5s  %5s  %5s  %5s  %5s  %6s  %s%s\n",
2274 	    object, doi.doi_indirection, iblk, dblk,
2275 	    asize, dnsize, lsize, fill, ZDB_OT_NAME(doi.doi_type), aux);
2276 
2277 	if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
2278 		(void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %5s  %6s  %s\n",
2279 		    "", "", "", "", "", "", bonus_size, "bonus",
2280 		    ZDB_OT_NAME(doi.doi_bonus_type));
2281 	}
2282 
2283 	if (verbosity >= 4) {
2284 		(void) printf("\tdnode flags: %s%s%s%s\n",
2285 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
2286 		    "USED_BYTES " : "",
2287 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
2288 		    "USERUSED_ACCOUNTED " : "",
2289 		    (dn->dn_phys->dn_flags & DNODE_FLAG_USEROBJUSED_ACCOUNTED) ?
2290 		    "USEROBJUSED_ACCOUNTED " : "",
2291 		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
2292 		    "SPILL_BLKPTR" : "");
2293 		(void) printf("\tdnode maxblkid: %llu\n",
2294 		    (longlong_t)dn->dn_phys->dn_maxblkid);
2295 
2296 		if (!dnode_held) {
2297 			object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os,
2298 			    object, bonus, bsize);
2299 		} else {
2300 			(void) printf("\t\t(bonus encrypted)\n");
2301 		}
2302 
2303 		if (!os->os_encrypted || !DMU_OT_IS_ENCRYPTED(doi.doi_type)) {
2304 			object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object,
2305 			    NULL, 0);
2306 		} else {
2307 			(void) printf("\t\t(object encrypted)\n");
2308 		}
2309 
2310 		*print_header = 1;
2311 	}
2312 
2313 	if (verbosity >= 5)
2314 		dump_indirect(dn);
2315 
2316 	if (verbosity >= 5) {
2317 		/*
2318 		 * Report the list of segments that comprise the object.
2319 		 */
2320 		uint64_t start = 0;
2321 		uint64_t end;
2322 		uint64_t blkfill = 1;
2323 		int minlvl = 1;
2324 
2325 		if (dn->dn_type == DMU_OT_DNODE) {
2326 			minlvl = 0;
2327 			blkfill = DNODES_PER_BLOCK;
2328 		}
2329 
2330 		for (;;) {
2331 			char segsize[32];
2332 			/* make sure nicenum has enough space */
2333 			CTASSERT(sizeof (segsize) >= NN_NUMBUF_SZ);
2334 			error = dnode_next_offset(dn,
2335 			    0, &start, minlvl, blkfill, 0);
2336 			if (error)
2337 				break;
2338 			end = start;
2339 			error = dnode_next_offset(dn,
2340 			    DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
2341 			zdb_nicenum(end - start, segsize, sizeof (segsize));
2342 			(void) printf("\t\tsegment [%016llx, %016llx)"
2343 			    " size %5s\n", (u_longlong_t)start,
2344 			    (u_longlong_t)end, segsize);
2345 			if (error)
2346 				break;
2347 			start = end;
2348 		}
2349 	}
2350 
2351 	if (db != NULL)
2352 		dmu_buf_rele(db, FTAG);
2353 	if (dnode_held)
2354 		dnode_rele(dn, FTAG);
2355 }
2356 
2357 static void
2358 count_dir_mos_objects(dsl_dir_t *dd)
2359 {
2360 	mos_obj_refd(dd->dd_object);
2361 	mos_obj_refd(dsl_dir_phys(dd)->dd_child_dir_zapobj);
2362 	mos_obj_refd(dsl_dir_phys(dd)->dd_deleg_zapobj);
2363 	mos_obj_refd(dsl_dir_phys(dd)->dd_props_zapobj);
2364 	mos_obj_refd(dsl_dir_phys(dd)->dd_clones);
2365 }
2366 
2367 static void
2368 count_ds_mos_objects(dsl_dataset_t *ds)
2369 {
2370 	mos_obj_refd(ds->ds_object);
2371 	mos_obj_refd(dsl_dataset_phys(ds)->ds_next_clones_obj);
2372 	mos_obj_refd(dsl_dataset_phys(ds)->ds_props_obj);
2373 	mos_obj_refd(dsl_dataset_phys(ds)->ds_userrefs_obj);
2374 	mos_obj_refd(dsl_dataset_phys(ds)->ds_snapnames_zapobj);
2375 
2376 	if (!dsl_dataset_is_snapshot(ds)) {
2377 		count_dir_mos_objects(ds->ds_dir);
2378 	}
2379 }
2380 
2381 static const char *objset_types[DMU_OST_NUMTYPES] = {
2382 	"NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
2383 
2384 static void
2385 dump_dir(objset_t *os)
2386 {
2387 	dmu_objset_stats_t dds;
2388 	uint64_t object, object_count;
2389 	uint64_t refdbytes, usedobjs, scratch;
2390 	char numbuf[32];
2391 	char blkbuf[BP_SPRINTF_LEN + 20];
2392 	char osname[ZFS_MAX_DATASET_NAME_LEN];
2393 	const char *type = "UNKNOWN";
2394 	int verbosity = dump_opt['d'];
2395 	int print_header = 1;
2396 	unsigned i;
2397 	int error;
2398 	uint64_t total_slots_used = 0;
2399 	uint64_t max_slot_used = 0;
2400 	uint64_t dnode_slots;
2401 
2402 	/* make sure nicenum has enough space */
2403 	CTASSERT(sizeof (numbuf) >= NN_NUMBUF_SZ);
2404 
2405 	dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
2406 	dmu_objset_fast_stat(os, &dds);
2407 	dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
2408 
2409 	if (dds.dds_type < DMU_OST_NUMTYPES)
2410 		type = objset_types[dds.dds_type];
2411 
2412 	if (dds.dds_type == DMU_OST_META) {
2413 		dds.dds_creation_txg = TXG_INITIAL;
2414 		usedobjs = BP_GET_FILL(os->os_rootbp);
2415 		refdbytes = dsl_dir_phys(os->os_spa->spa_dsl_pool->dp_mos_dir)->
2416 		    dd_used_bytes;
2417 	} else {
2418 		dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
2419 	}
2420 
2421 	ASSERT3U(usedobjs, ==, BP_GET_FILL(os->os_rootbp));
2422 
2423 	zdb_nicenum(refdbytes, numbuf, sizeof (numbuf));
2424 
2425 	if (verbosity >= 4) {
2426 		(void) snprintf(blkbuf, sizeof (blkbuf), ", rootbp ");
2427 		(void) snprintf_blkptr(blkbuf + strlen(blkbuf),
2428 		    sizeof (blkbuf) - strlen(blkbuf), os->os_rootbp);
2429 	} else {
2430 		blkbuf[0] = '\0';
2431 	}
2432 
2433 	dmu_objset_name(os, osname);
2434 
2435 	(void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
2436 	    "%s, %llu objects%s%s\n",
2437 	    osname, type, (u_longlong_t)dmu_objset_id(os),
2438 	    (u_longlong_t)dds.dds_creation_txg,
2439 	    numbuf, (u_longlong_t)usedobjs, blkbuf,
2440 	    (dds.dds_inconsistent) ? " (inconsistent)" : "");
2441 
2442 	if (zopt_objects != 0) {
2443 		for (i = 0; i < zopt_objects; i++)
2444 			dump_object(os, zopt_object[i], verbosity,
2445 			    &print_header, NULL);
2446 		(void) printf("\n");
2447 		return;
2448 	}
2449 
2450 	if (dump_opt['i'] != 0 || verbosity >= 2)
2451 		dump_intent_log(dmu_objset_zil(os));
2452 
2453 	if (dmu_objset_ds(os) != NULL) {
2454 		dsl_dataset_t *ds = dmu_objset_ds(os);
2455 		dump_deadlist(&ds->ds_deadlist);
2456 
2457 		if (dsl_dataset_remap_deadlist_exists(ds)) {
2458 			(void) printf("ds_remap_deadlist:\n");
2459 			dump_deadlist(&ds->ds_remap_deadlist);
2460 		}
2461 		count_ds_mos_objects(ds);
2462 	}
2463 
2464 	if (verbosity < 2)
2465 		return;
2466 
2467 	if (BP_IS_HOLE(os->os_rootbp))
2468 		return;
2469 
2470 	dump_object(os, 0, verbosity, &print_header, NULL);
2471 	object_count = 0;
2472 	if (DMU_USERUSED_DNODE(os) != NULL &&
2473 	    DMU_USERUSED_DNODE(os)->dn_type != 0) {
2474 		dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header,
2475 		    NULL);
2476 		dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header,
2477 		    NULL);
2478 	}
2479 
2480 	if (DMU_PROJECTUSED_DNODE(os) != NULL &&
2481 	    DMU_PROJECTUSED_DNODE(os)->dn_type != 0)
2482 		dump_object(os, DMU_PROJECTUSED_OBJECT, verbosity,
2483 		    &print_header, NULL);
2484 
2485 	object = 0;
2486 	while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
2487 		dump_object(os, object, verbosity, &print_header, &dnode_slots);
2488 		object_count++;
2489 		total_slots_used += dnode_slots;
2490 		max_slot_used = object + dnode_slots - 1;
2491 	}
2492 
2493 	(void) printf("\n");
2494 
2495 	(void) printf("    Dnode slots:\n");
2496 	(void) printf("\tTotal used:    %10llu\n",
2497 	    (u_longlong_t)total_slots_used);
2498 	(void) printf("\tMax used:      %10llu\n",
2499 	    (u_longlong_t)max_slot_used);
2500 	(void) printf("\tPercent empty: %10lf\n",
2501 	    (double)(max_slot_used - total_slots_used)*100 /
2502 	    (double)max_slot_used);
2503 
2504 	(void) printf("\n");
2505 
2506 	if (error != ESRCH) {
2507 		(void) fprintf(stderr, "dmu_object_next() = %d\n", error);
2508 		abort();
2509 	}
2510 	if (leaked_objects != 0) {
2511 		(void) printf("%d potentially leaked objects detected\n",
2512 		    leaked_objects);
2513 		leaked_objects = 0;
2514 	}
2515 
2516 	ASSERT3U(object_count, ==, usedobjs);
2517 }
2518 
2519 static void
2520 dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
2521 {
2522 	time_t timestamp = ub->ub_timestamp;
2523 
2524 	(void) printf("%s", header ? header : "");
2525 	(void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
2526 	(void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
2527 	(void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
2528 	(void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
2529 	(void) printf("\ttimestamp = %llu UTC = %s",
2530 	    (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
2531 
2532 	(void) printf("\tmmp_magic = %016llx\n",
2533 	    (u_longlong_t)ub->ub_mmp_magic);
2534 	if (MMP_VALID(ub)) {
2535 		(void) printf("\tmmp_delay = %0llu\n",
2536 		    (u_longlong_t)ub->ub_mmp_delay);
2537 		if (MMP_SEQ_VALID(ub))
2538 			(void) printf("\tmmp_seq = %u\n",
2539 			    (unsigned int) MMP_SEQ(ub));
2540 		if (MMP_FAIL_INT_VALID(ub))
2541 			(void) printf("\tmmp_fail = %u\n",
2542 			    (unsigned int) MMP_FAIL_INT(ub));
2543 		if (MMP_INTERVAL_VALID(ub))
2544 			(void) printf("\tmmp_write = %u\n",
2545 			    (unsigned int) MMP_INTERVAL(ub));
2546 		/* After MMP_* to make summarize_uberblock_mmp cleaner */
2547 		(void) printf("\tmmp_valid = %x\n",
2548 		    (unsigned int) ub->ub_mmp_config & 0xFF);
2549 	}
2550 
2551 	if (dump_opt['u'] >= 3) {
2552 		char blkbuf[BP_SPRINTF_LEN];
2553 		snprintf_blkptr(blkbuf, sizeof (blkbuf), &ub->ub_rootbp);
2554 		(void) printf("\trootbp = %s\n", blkbuf);
2555 	}
2556 	(void) printf("\tcheckpoint_txg = %llu\n",
2557 	    (u_longlong_t)ub->ub_checkpoint_txg);
2558 	(void) printf("%s", footer ? footer : "");
2559 }
2560 
2561 static void
2562 dump_config(spa_t *spa)
2563 {
2564 	dmu_buf_t *db;
2565 	size_t nvsize = 0;
2566 	int error = 0;
2567 
2568 
2569 	error = dmu_bonus_hold(spa->spa_meta_objset,
2570 	    spa->spa_config_object, FTAG, &db);
2571 
2572 	if (error == 0) {
2573 		nvsize = *(uint64_t *)db->db_data;
2574 		dmu_buf_rele(db, FTAG);
2575 
2576 		(void) printf("\nMOS Configuration:\n");
2577 		dump_packed_nvlist(spa->spa_meta_objset,
2578 		    spa->spa_config_object, (void *)&nvsize, 1);
2579 	} else {
2580 		(void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
2581 		    (u_longlong_t)spa->spa_config_object, error);
2582 	}
2583 }
2584 
2585 static void
2586 dump_cachefile(const char *cachefile)
2587 {
2588 	int fd;
2589 	struct stat64 statbuf;
2590 	char *buf;
2591 	nvlist_t *config;
2592 
2593 	if ((fd = open64(cachefile, O_RDONLY)) < 0) {
2594 		(void) printf("cannot open '%s': %s\n", cachefile,
2595 		    strerror(errno));
2596 		exit(1);
2597 	}
2598 
2599 	if (fstat64(fd, &statbuf) != 0) {
2600 		(void) printf("failed to stat '%s': %s\n", cachefile,
2601 		    strerror(errno));
2602 		exit(1);
2603 	}
2604 
2605 	if ((buf = malloc(statbuf.st_size)) == NULL) {
2606 		(void) fprintf(stderr, "failed to allocate %llu bytes\n",
2607 		    (u_longlong_t)statbuf.st_size);
2608 		exit(1);
2609 	}
2610 
2611 	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
2612 		(void) fprintf(stderr, "failed to read %llu bytes\n",
2613 		    (u_longlong_t)statbuf.st_size);
2614 		exit(1);
2615 	}
2616 
2617 	(void) close(fd);
2618 
2619 	if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
2620 		(void) fprintf(stderr, "failed to unpack nvlist\n");
2621 		exit(1);
2622 	}
2623 
2624 	free(buf);
2625 
2626 	dump_nvlist(config, 0);
2627 
2628 	nvlist_free(config);
2629 }
2630 
2631 #define	ZDB_MAX_UB_HEADER_SIZE 32
2632 
2633 static void
2634 dump_label_uberblocks(vdev_label_t *lbl, uint64_t ashift)
2635 {
2636 	vdev_t vd;
2637 	vdev_t *vdp = &vd;
2638 	char header[ZDB_MAX_UB_HEADER_SIZE];
2639 
2640 	vd.vdev_ashift = ashift;
2641 	vdp->vdev_top = vdp;
2642 
2643 	for (int i = 0; i < VDEV_UBERBLOCK_COUNT(vdp); i++) {
2644 		uint64_t uoff = VDEV_UBERBLOCK_OFFSET(vdp, i);
2645 		uberblock_t *ub = (void *)((char *)lbl + uoff);
2646 
2647 		if (uberblock_verify(ub))
2648 			continue;
2649 
2650 		if ((dump_opt['u'] < 4) &&
2651 		    (ub->ub_mmp_magic == MMP_MAGIC) && ub->ub_mmp_delay &&
2652 		    (i >= VDEV_UBERBLOCK_COUNT(&vd) - MMP_BLOCKS_PER_LABEL))
2653 			continue;
2654 
2655 		(void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
2656 		    "Uberblock[%d]\n", i);
2657 		dump_uberblock(ub, header, "");
2658 	}
2659 }
2660 
2661 static char curpath[PATH_MAX];
2662 
2663 /*
2664  * Iterate through the path components, recursively passing
2665  * current one's obj and remaining path until we find the obj
2666  * for the last one.
2667  */
2668 static int
2669 dump_path_impl(objset_t *os, uint64_t obj, char *name)
2670 {
2671 	int err;
2672 	int header = 1;
2673 	uint64_t child_obj;
2674 	char *s;
2675 	dmu_buf_t *db;
2676 	dmu_object_info_t doi;
2677 
2678 	if ((s = strchr(name, '/')) != NULL)
2679 		*s = '\0';
2680 	err = zap_lookup(os, obj, name, 8, 1, &child_obj);
2681 
2682 	(void) strlcat(curpath, name, sizeof (curpath));
2683 
2684 	if (err != 0) {
2685 		(void) fprintf(stderr, "failed to lookup %s: %s\n",
2686 		    curpath, strerror(err));
2687 		return (err);
2688 	}
2689 
2690 	child_obj = ZFS_DIRENT_OBJ(child_obj);
2691 	err = sa_buf_hold(os, child_obj, FTAG, &db);
2692 	if (err != 0) {
2693 		(void) fprintf(stderr,
2694 		    "failed to get SA dbuf for obj %llu: %s\n",
2695 		    (u_longlong_t)child_obj, strerror(err));
2696 		return (EINVAL);
2697 	}
2698 	dmu_object_info_from_db(db, &doi);
2699 	sa_buf_rele(db, FTAG);
2700 
2701 	if (doi.doi_bonus_type != DMU_OT_SA &&
2702 	    doi.doi_bonus_type != DMU_OT_ZNODE) {
2703 		(void) fprintf(stderr, "invalid bonus type %d for obj %llu\n",
2704 		    doi.doi_bonus_type, (u_longlong_t)child_obj);
2705 		return (EINVAL);
2706 	}
2707 
2708 	if (dump_opt['v'] > 6) {
2709 		(void) printf("obj=%llu %s type=%d bonustype=%d\n",
2710 		    (u_longlong_t)child_obj, curpath, doi.doi_type,
2711 		    doi.doi_bonus_type);
2712 	}
2713 
2714 	(void) strlcat(curpath, "/", sizeof (curpath));
2715 
2716 	switch (doi.doi_type) {
2717 	case DMU_OT_DIRECTORY_CONTENTS:
2718 		if (s != NULL && *(s + 1) != '\0')
2719 			return (dump_path_impl(os, child_obj, s + 1));
2720 		/*FALLTHROUGH*/
2721 	case DMU_OT_PLAIN_FILE_CONTENTS:
2722 		dump_object(os, child_obj, dump_opt['v'], &header, NULL);
2723 		return (0);
2724 	default:
2725 		(void) fprintf(stderr, "object %llu has non-file/directory "
2726 		    "type %d\n", (u_longlong_t)obj, doi.doi_type);
2727 		break;
2728 	}
2729 
2730 	return (EINVAL);
2731 }
2732 
2733 /*
2734  * Dump the blocks for the object specified by path inside the dataset.
2735  */
2736 static int
2737 dump_path(char *ds, char *path)
2738 {
2739 	int err;
2740 	objset_t *os;
2741 	uint64_t root_obj;
2742 
2743 	err = open_objset(ds, DMU_OST_ZFS, FTAG, &os);
2744 	if (err != 0)
2745 		return (err);
2746 
2747 	err = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1, &root_obj);
2748 	if (err != 0) {
2749 		(void) fprintf(stderr, "can't lookup root znode: %s\n",
2750 		    strerror(err));
2751 		dmu_objset_disown(os, B_FALSE, FTAG);
2752 		return (EINVAL);
2753 	}
2754 
2755 	(void) snprintf(curpath, sizeof (curpath), "dataset=%s path=/", ds);
2756 
2757 	err = dump_path_impl(os, root_obj, path);
2758 
2759 	close_objset(os, FTAG);
2760 	return (err);
2761 }
2762 
2763 static int
2764 dump_label(const char *dev)
2765 {
2766 	int fd;
2767 	vdev_label_t label;
2768 	char path[MAXPATHLEN];
2769 	char *buf = label.vl_vdev_phys.vp_nvlist;
2770 	size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
2771 	struct stat64 statbuf;
2772 	uint64_t psize, ashift;
2773 	boolean_t label_found = B_FALSE;
2774 
2775 	(void) strlcpy(path, dev, sizeof (path));
2776 	if (dev[0] == '/') {
2777 		if (strncmp(dev, ZFS_DISK_ROOTD,
2778 		    strlen(ZFS_DISK_ROOTD)) == 0) {
2779 			(void) snprintf(path, sizeof (path), "%s%s",
2780 			    ZFS_RDISK_ROOTD, dev + strlen(ZFS_DISK_ROOTD));
2781 		}
2782 	} else if (stat64(path, &statbuf) != 0) {
2783 		char *s;
2784 
2785 		(void) snprintf(path, sizeof (path), "%s%s", ZFS_RDISK_ROOTD,
2786 		    dev);
2787 		if (((s = strrchr(dev, 's')) == NULL &&
2788 		    (s = strchr(dev, 'p')) == NULL) ||
2789 		    !isdigit(*(s + 1)))
2790 			(void) strlcat(path, "s0", sizeof (path));
2791 	}
2792 
2793 	if ((fd = open64(path, O_RDONLY)) < 0) {
2794 		(void) fprintf(stderr, "cannot open '%s': %s\n", path,
2795 		    strerror(errno));
2796 		exit(1);
2797 	}
2798 
2799 	if (fstat64(fd, &statbuf) != 0) {
2800 		(void) fprintf(stderr, "failed to stat '%s': %s\n", path,
2801 		    strerror(errno));
2802 		(void) close(fd);
2803 		exit(1);
2804 	}
2805 
2806 	if (S_ISBLK(statbuf.st_mode)) {
2807 		(void) fprintf(stderr,
2808 		    "cannot use '%s': character device required\n", path);
2809 		(void) close(fd);
2810 		exit(1);
2811 	}
2812 
2813 	psize = statbuf.st_size;
2814 	psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
2815 
2816 	for (int l = 0; l < VDEV_LABELS; l++) {
2817 		nvlist_t *config = NULL;
2818 
2819 		if (!dump_opt['q']) {
2820 			(void) printf("------------------------------------\n");
2821 			(void) printf("LABEL %d\n", l);
2822 			(void) printf("------------------------------------\n");
2823 		}
2824 
2825 		if (pread64(fd, &label, sizeof (label),
2826 		    vdev_label_offset(psize, l, 0)) != sizeof (label)) {
2827 			if (!dump_opt['q'])
2828 				(void) printf("failed to read label %d\n", l);
2829 			continue;
2830 		}
2831 
2832 		if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
2833 			if (!dump_opt['q'])
2834 				(void) printf("failed to unpack label %d\n", l);
2835 			ashift = SPA_MINBLOCKSHIFT;
2836 		} else {
2837 			nvlist_t *vdev_tree = NULL;
2838 
2839 			if (!dump_opt['q'])
2840 				dump_nvlist(config, 4);
2841 			if ((nvlist_lookup_nvlist(config,
2842 			    ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
2843 			    (nvlist_lookup_uint64(vdev_tree,
2844 			    ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
2845 				ashift = SPA_MINBLOCKSHIFT;
2846 			nvlist_free(config);
2847 			label_found = B_TRUE;
2848 		}
2849 		if (dump_opt['u'])
2850 			dump_label_uberblocks(&label, ashift);
2851 	}
2852 
2853 	(void) close(fd);
2854 
2855 	return (label_found ? 0 : 2);
2856 }
2857 
2858 static uint64_t dataset_feature_count[SPA_FEATURES];
2859 static uint64_t remap_deadlist_count = 0;
2860 
2861 /*ARGSUSED*/
2862 static int
2863 dump_one_dir(const char *dsname, void *arg)
2864 {
2865 	int error;
2866 	objset_t *os;
2867 
2868 	error = open_objset(dsname, DMU_OST_ANY, FTAG, &os);
2869 	if (error != 0)
2870 		return (0);
2871 
2872 	for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
2873 		if (!dmu_objset_ds(os)->ds_feature_inuse[f])
2874 			continue;
2875 		ASSERT(spa_feature_table[f].fi_flags &
2876 		    ZFEATURE_FLAG_PER_DATASET);
2877 		dataset_feature_count[f]++;
2878 	}
2879 
2880 	if (dsl_dataset_remap_deadlist_exists(dmu_objset_ds(os))) {
2881 		remap_deadlist_count++;
2882 	}
2883 
2884 	dump_dir(os);
2885 	close_objset(os, FTAG);
2886 	fuid_table_destroy();
2887 	return (0);
2888 }
2889 
2890 /*
2891  * Block statistics.
2892  */
2893 #define	PSIZE_HISTO_SIZE (SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 2)
2894 typedef struct zdb_blkstats {
2895 	uint64_t zb_asize;
2896 	uint64_t zb_lsize;
2897 	uint64_t zb_psize;
2898 	uint64_t zb_count;
2899 	uint64_t zb_gangs;
2900 	uint64_t zb_ditto_samevdev;
2901 	uint64_t zb_ditto_same_ms;
2902 	uint64_t zb_psize_histogram[PSIZE_HISTO_SIZE];
2903 } zdb_blkstats_t;
2904 
2905 /*
2906  * Extended object types to report deferred frees and dedup auto-ditto blocks.
2907  */
2908 #define	ZDB_OT_DEFERRED	(DMU_OT_NUMTYPES + 0)
2909 #define	ZDB_OT_DITTO	(DMU_OT_NUMTYPES + 1)
2910 #define	ZDB_OT_OTHER	(DMU_OT_NUMTYPES + 2)
2911 #define	ZDB_OT_TOTAL	(DMU_OT_NUMTYPES + 3)
2912 
2913 static const char *zdb_ot_extname[] = {
2914 	"deferred free",
2915 	"dedup ditto",
2916 	"other",
2917 	"Total",
2918 };
2919 
2920 #define	ZB_TOTAL	DN_MAX_LEVELS
2921 
2922 typedef struct zdb_cb {
2923 	zdb_blkstats_t	zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
2924 	uint64_t	zcb_removing_size;
2925 	uint64_t	zcb_checkpoint_size;
2926 	uint64_t	zcb_dedup_asize;
2927 	uint64_t	zcb_dedup_blocks;
2928 	uint64_t	zcb_embedded_blocks[NUM_BP_EMBEDDED_TYPES];
2929 	uint64_t	zcb_embedded_histogram[NUM_BP_EMBEDDED_TYPES]
2930 	    [BPE_PAYLOAD_SIZE];
2931 	uint64_t	zcb_start;
2932 	hrtime_t	zcb_lastprint;
2933 	uint64_t	zcb_totalasize;
2934 	uint64_t	zcb_errors[256];
2935 	int		zcb_readfails;
2936 	int		zcb_haderrors;
2937 	spa_t		*zcb_spa;
2938 	uint32_t	**zcb_vd_obsolete_counts;
2939 } zdb_cb_t;
2940 
2941 /* test if two DVA offsets from same vdev are within the same metaslab */
2942 static boolean_t
2943 same_metaslab(spa_t *spa, uint64_t vdev, uint64_t off1, uint64_t off2)
2944 {
2945 	vdev_t *vd = vdev_lookup_top(spa, vdev);
2946 	uint64_t ms_shift = vd->vdev_ms_shift;
2947 
2948 	return ((off1 >> ms_shift) == (off2 >> ms_shift));
2949 }
2950 
2951 static void
2952 zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
2953     dmu_object_type_t type)
2954 {
2955 	uint64_t refcnt = 0;
2956 
2957 	ASSERT(type < ZDB_OT_TOTAL);
2958 
2959 	if (zilog && zil_bp_tree_add(zilog, bp) != 0)
2960 		return;
2961 
2962 	spa_config_enter(zcb->zcb_spa, SCL_CONFIG, FTAG, RW_READER);
2963 
2964 	for (int i = 0; i < 4; i++) {
2965 		int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
2966 		int t = (i & 1) ? type : ZDB_OT_TOTAL;
2967 		int equal;
2968 		zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
2969 
2970 		zb->zb_asize += BP_GET_ASIZE(bp);
2971 		zb->zb_lsize += BP_GET_LSIZE(bp);
2972 		zb->zb_psize += BP_GET_PSIZE(bp);
2973 		zb->zb_count++;
2974 
2975 		/*
2976 		 * The histogram is only big enough to record blocks up to
2977 		 * SPA_OLD_MAXBLOCKSIZE; larger blocks go into the last,
2978 		 * "other", bucket.
2979 		 */
2980 		unsigned idx = BP_GET_PSIZE(bp) >> SPA_MINBLOCKSHIFT;
2981 		idx = MIN(idx, SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 1);
2982 		zb->zb_psize_histogram[idx]++;
2983 
2984 		zb->zb_gangs += BP_COUNT_GANG(bp);
2985 
2986 		switch (BP_GET_NDVAS(bp)) {
2987 		case 2:
2988 			if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2989 			    DVA_GET_VDEV(&bp->blk_dva[1])) {
2990 				zb->zb_ditto_samevdev++;
2991 
2992 				if (same_metaslab(zcb->zcb_spa,
2993 				    DVA_GET_VDEV(&bp->blk_dva[0]),
2994 				    DVA_GET_OFFSET(&bp->blk_dva[0]),
2995 				    DVA_GET_OFFSET(&bp->blk_dva[1])))
2996 					zb->zb_ditto_same_ms++;
2997 			}
2998 			break;
2999 		case 3:
3000 			equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3001 			    DVA_GET_VDEV(&bp->blk_dva[1])) +
3002 			    (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3003 			    DVA_GET_VDEV(&bp->blk_dva[2])) +
3004 			    (DVA_GET_VDEV(&bp->blk_dva[1]) ==
3005 			    DVA_GET_VDEV(&bp->blk_dva[2]));
3006 			if (equal != 0) {
3007 				zb->zb_ditto_samevdev++;
3008 
3009 				if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3010 				    DVA_GET_VDEV(&bp->blk_dva[1]) &&
3011 				    same_metaslab(zcb->zcb_spa,
3012 				    DVA_GET_VDEV(&bp->blk_dva[0]),
3013 				    DVA_GET_OFFSET(&bp->blk_dva[0]),
3014 				    DVA_GET_OFFSET(&bp->blk_dva[1])))
3015 					zb->zb_ditto_same_ms++;
3016 				else if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
3017 				    DVA_GET_VDEV(&bp->blk_dva[2]) &&
3018 				    same_metaslab(zcb->zcb_spa,
3019 				    DVA_GET_VDEV(&bp->blk_dva[0]),
3020 				    DVA_GET_OFFSET(&bp->blk_dva[0]),
3021 				    DVA_GET_OFFSET(&bp->blk_dva[2])))
3022 					zb->zb_ditto_same_ms++;
3023 				else if (DVA_GET_VDEV(&bp->blk_dva[1]) ==
3024 				    DVA_GET_VDEV(&bp->blk_dva[2]) &&
3025 				    same_metaslab(zcb->zcb_spa,
3026 				    DVA_GET_VDEV(&bp->blk_dva[1]),
3027 				    DVA_GET_OFFSET(&bp->blk_dva[1]),
3028 				    DVA_GET_OFFSET(&bp->blk_dva[2])))
3029 					zb->zb_ditto_same_ms++;
3030 			}
3031 			break;
3032 		}
3033 	}
3034 
3035 	spa_config_exit(zcb->zcb_spa, SCL_CONFIG, FTAG);
3036 
3037 	if (BP_IS_EMBEDDED(bp)) {
3038 		zcb->zcb_embedded_blocks[BPE_GET_ETYPE(bp)]++;
3039 		zcb->zcb_embedded_histogram[BPE_GET_ETYPE(bp)]
3040 		    [BPE_GET_PSIZE(bp)]++;
3041 		return;
3042 	}
3043 
3044 	if (dump_opt['L'])
3045 		return;
3046 
3047 	if (BP_GET_DEDUP(bp)) {
3048 		ddt_t *ddt;
3049 		ddt_entry_t *dde;
3050 
3051 		ddt = ddt_select(zcb->zcb_spa, bp);
3052 		ddt_enter(ddt);
3053 		dde = ddt_lookup(ddt, bp, B_FALSE);
3054 
3055 		if (dde == NULL) {
3056 			refcnt = 0;
3057 		} else {
3058 			ddt_phys_t *ddp = ddt_phys_select(dde, bp);
3059 			ddt_phys_decref(ddp);
3060 			refcnt = ddp->ddp_refcnt;
3061 			if (ddt_phys_total_refcnt(dde) == 0)
3062 				ddt_remove(ddt, dde);
3063 		}
3064 		ddt_exit(ddt);
3065 	}
3066 
3067 	VERIFY3U(zio_wait(zio_claim(NULL, zcb->zcb_spa,
3068 	    refcnt ? 0 : spa_min_claim_txg(zcb->zcb_spa),
3069 	    bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
3070 }
3071 
3072 static void
3073 zdb_blkptr_done(zio_t *zio)
3074 {
3075 	spa_t *spa = zio->io_spa;
3076 	blkptr_t *bp = zio->io_bp;
3077 	int ioerr = zio->io_error;
3078 	zdb_cb_t *zcb = zio->io_private;
3079 	zbookmark_phys_t *zb = &zio->io_bookmark;
3080 
3081 	abd_free(zio->io_abd);
3082 
3083 	mutex_enter(&spa->spa_scrub_lock);
3084 	spa->spa_load_verify_ios--;
3085 	cv_broadcast(&spa->spa_scrub_io_cv);
3086 
3087 	if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
3088 		char blkbuf[BP_SPRINTF_LEN];
3089 
3090 		zcb->zcb_haderrors = 1;
3091 		zcb->zcb_errors[ioerr]++;
3092 
3093 		if (dump_opt['b'] >= 2)
3094 			snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
3095 		else
3096 			blkbuf[0] = '\0';
3097 
3098 		(void) printf("zdb_blkptr_cb: "
3099 		    "Got error %d reading "
3100 		    "<%llu, %llu, %lld, %llx> %s -- skipping\n",
3101 		    ioerr,
3102 		    (u_longlong_t)zb->zb_objset,
3103 		    (u_longlong_t)zb->zb_object,
3104 		    (u_longlong_t)zb->zb_level,
3105 		    (u_longlong_t)zb->zb_blkid,
3106 		    blkbuf);
3107 	}
3108 	mutex_exit(&spa->spa_scrub_lock);
3109 }
3110 
3111 static int
3112 zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
3113     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
3114 {
3115 	zdb_cb_t *zcb = arg;
3116 	dmu_object_type_t type;
3117 	boolean_t is_metadata;
3118 
3119 	if (bp == NULL)
3120 		return (0);
3121 
3122 	if (dump_opt['b'] >= 5 && bp->blk_birth > 0) {
3123 		char blkbuf[BP_SPRINTF_LEN];
3124 		snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
3125 		(void) printf("objset %llu object %llu "
3126 		    "level %lld offset 0x%llx %s\n",
3127 		    (u_longlong_t)zb->zb_objset,
3128 		    (u_longlong_t)zb->zb_object,
3129 		    (longlong_t)zb->zb_level,
3130 		    (u_longlong_t)blkid2offset(dnp, bp, zb),
3131 		    blkbuf);
3132 	}
3133 
3134 	if (BP_IS_HOLE(bp))
3135 		return (0);
3136 
3137 	type = BP_GET_TYPE(bp);
3138 
3139 	zdb_count_block(zcb, zilog, bp,
3140 	    (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
3141 
3142 	is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
3143 
3144 	if (!BP_IS_EMBEDDED(bp) &&
3145 	    (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata))) {
3146 		size_t size = BP_GET_PSIZE(bp);
3147 		abd_t *abd = abd_alloc(size, B_FALSE);
3148 		int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
3149 
3150 		/* If it's an intent log block, failure is expected. */
3151 		if (zb->zb_level == ZB_ZIL_LEVEL)
3152 			flags |= ZIO_FLAG_SPECULATIVE;
3153 
3154 		mutex_enter(&spa->spa_scrub_lock);
3155 		while (spa->spa_load_verify_ios > max_inflight)
3156 			cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
3157 		spa->spa_load_verify_ios++;
3158 		mutex_exit(&spa->spa_scrub_lock);
3159 
3160 		zio_nowait(zio_read(NULL, spa, bp, abd, size,
3161 		    zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
3162 	}
3163 
3164 	zcb->zcb_readfails = 0;
3165 
3166 	/* only call gethrtime() every 100 blocks */
3167 	static int iters;
3168 	if (++iters > 100)
3169 		iters = 0;
3170 	else
3171 		return (0);
3172 
3173 	if (dump_opt['b'] < 5 && gethrtime() > zcb->zcb_lastprint + NANOSEC) {
3174 		uint64_t now = gethrtime();
3175 		char buf[10];
3176 		uint64_t bytes = zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL].zb_asize;
3177 		int kb_per_sec =
3178 		    1 + bytes / (1 + ((now - zcb->zcb_start) / 1000 / 1000));
3179 		int sec_remaining =
3180 		    (zcb->zcb_totalasize - bytes) / 1024 / kb_per_sec;
3181 
3182 		/* make sure nicenum has enough space */
3183 		CTASSERT(sizeof (buf) >= NN_NUMBUF_SZ);
3184 
3185 		zfs_nicenum(bytes, buf, sizeof (buf));
3186 		(void) fprintf(stderr,
3187 		    "\r%5s completed (%4dMB/s) "
3188 		    "estimated time remaining: %uhr %02umin %02usec        ",
3189 		    buf, kb_per_sec / 1024,
3190 		    sec_remaining / 60 / 60,
3191 		    sec_remaining / 60 % 60,
3192 		    sec_remaining % 60);
3193 
3194 		zcb->zcb_lastprint = now;
3195 	}
3196 
3197 	return (0);
3198 }
3199 
3200 static void
3201 zdb_leak(void *arg, uint64_t start, uint64_t size)
3202 {
3203 	vdev_t *vd = arg;
3204 
3205 	(void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
3206 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
3207 }
3208 
3209 static metaslab_ops_t zdb_metaslab_ops = {
3210 	NULL	/* alloc */
3211 };
3212 
3213 typedef int (*zdb_log_sm_cb_t)(spa_t *spa, space_map_entry_t *sme,
3214     uint64_t txg, void *arg);
3215 
3216 typedef struct unflushed_iter_cb_arg {
3217 	spa_t *uic_spa;
3218 	uint64_t uic_txg;
3219 	void *uic_arg;
3220 	zdb_log_sm_cb_t uic_cb;
3221 } unflushed_iter_cb_arg_t;
3222 
3223 static int
3224 iterate_through_spacemap_logs_cb(space_map_entry_t *sme, void *arg)
3225 {
3226 	unflushed_iter_cb_arg_t *uic = arg;
3227 
3228 	return (uic->uic_cb(uic->uic_spa, sme, uic->uic_txg, uic->uic_arg));
3229 }
3230 
3231 static void
3232 iterate_through_spacemap_logs(spa_t *spa, zdb_log_sm_cb_t cb, void *arg)
3233 {
3234 	if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
3235 		return;
3236 
3237 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3238 	for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
3239 	    sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls)) {
3240 		space_map_t *sm = NULL;
3241 		VERIFY0(space_map_open(&sm, spa_meta_objset(spa),
3242 		    sls->sls_sm_obj, 0, UINT64_MAX, SPA_MINBLOCKSHIFT));
3243 
3244 		unflushed_iter_cb_arg_t uic = {
3245 			.uic_spa = spa,
3246 			.uic_txg = sls->sls_txg,
3247 			.uic_arg = arg,
3248 			.uic_cb = cb
3249 		};
3250 
3251 		VERIFY0(space_map_iterate(sm, space_map_length(sm),
3252 		    iterate_through_spacemap_logs_cb, &uic));
3253 		space_map_close(sm);
3254 	}
3255 	spa_config_exit(spa, SCL_CONFIG, FTAG);
3256 }
3257 
3258 /* ARGSUSED */
3259 static int
3260 load_unflushed_svr_segs_cb(spa_t *spa, space_map_entry_t *sme,
3261     uint64_t txg, void *arg)
3262 {
3263 	spa_vdev_removal_t *svr = arg;
3264 
3265 	uint64_t offset = sme->sme_offset;
3266 	uint64_t size = sme->sme_run;
3267 
3268 	/* skip vdevs we don't care about */
3269 	if (sme->sme_vdev != svr->svr_vdev_id)
3270 		return (0);
3271 
3272 	vdev_t *vd = vdev_lookup_top(spa, sme->sme_vdev);
3273 	metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
3274 	ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
3275 
3276 	if (txg < metaslab_unflushed_txg(ms))
3277 		return (0);
3278 
3279 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3280 	ASSERT(vim != NULL);
3281 	if (offset >= vdev_indirect_mapping_max_offset(vim))
3282 		return (0);
3283 
3284 	if (sme->sme_type == SM_ALLOC)
3285 		range_tree_add(svr->svr_allocd_segs, offset, size);
3286 	else
3287 		range_tree_remove(svr->svr_allocd_segs, offset, size);
3288 
3289 	return (0);
3290 }
3291 
3292 static void
3293 zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
3294 {
3295 	ddt_bookmark_t ddb;
3296 	ddt_entry_t dde;
3297 	int error;
3298 
3299 	ASSERT(!dump_opt['L']);
3300 
3301 	bzero(&ddb, sizeof (ddb));
3302 	while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
3303 		blkptr_t blk;
3304 		ddt_phys_t *ddp = dde.dde_phys;
3305 
3306 		if (ddb.ddb_class == DDT_CLASS_UNIQUE)
3307 			return;
3308 
3309 		ASSERT(ddt_phys_total_refcnt(&dde) > 1);
3310 
3311 		for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
3312 			if (ddp->ddp_phys_birth == 0)
3313 				continue;
3314 			ddt_bp_create(ddb.ddb_checksum,
3315 			    &dde.dde_key, ddp, &blk);
3316 			if (p == DDT_PHYS_DITTO) {
3317 				zdb_count_block(zcb, NULL, &blk, ZDB_OT_DITTO);
3318 			} else {
3319 				zcb->zcb_dedup_asize +=
3320 				    BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
3321 				zcb->zcb_dedup_blocks++;
3322 			}
3323 		}
3324 		ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
3325 		ddt_enter(ddt);
3326 		VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
3327 		ddt_exit(ddt);
3328 	}
3329 
3330 	ASSERT(error == ENOENT);
3331 }
3332 
3333 /* ARGSUSED */
3334 static void
3335 claim_segment_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
3336     uint64_t size, void *arg)
3337 {
3338 	/*
3339 	 * This callback was called through a remap from
3340 	 * a device being removed. Therefore, the vdev that
3341 	 * this callback is applied to is a concrete
3342 	 * vdev.
3343 	 */
3344 	ASSERT(vdev_is_concrete(vd));
3345 
3346 	VERIFY0(metaslab_claim_impl(vd, offset, size,
3347 	    spa_min_claim_txg(vd->vdev_spa)));
3348 }
3349 
3350 static void
3351 claim_segment_cb(void *arg, uint64_t offset, uint64_t size)
3352 {
3353 	vdev_t *vd = arg;
3354 
3355 	vdev_indirect_ops.vdev_op_remap(vd, offset, size,
3356 	    claim_segment_impl_cb, NULL);
3357 }
3358 
3359 /*
3360  * After accounting for all allocated blocks that are directly referenced,
3361  * we might have missed a reference to a block from a partially complete
3362  * (and thus unused) indirect mapping object. We perform a secondary pass
3363  * through the metaslabs we have already mapped and claim the destination
3364  * blocks.
3365  */
3366 static void
3367 zdb_claim_removing(spa_t *spa, zdb_cb_t *zcb)
3368 {
3369 	if (dump_opt['L'])
3370 		return;
3371 
3372 	if (spa->spa_vdev_removal == NULL)
3373 		return;
3374 
3375 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3376 
3377 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
3378 	vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
3379 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3380 
3381 	ASSERT0(range_tree_space(svr->svr_allocd_segs));
3382 
3383 	range_tree_t *allocs = range_tree_create(NULL, RANGE_SEG64, NULL, 0, 0);
3384 	for (uint64_t msi = 0; msi < vd->vdev_ms_count; msi++) {
3385 		metaslab_t *msp = vd->vdev_ms[msi];
3386 
3387 		if (msp->ms_start >= vdev_indirect_mapping_max_offset(vim))
3388 			break;
3389 
3390 		ASSERT0(range_tree_space(allocs));
3391 		if (msp->ms_sm != NULL)
3392 			VERIFY0(space_map_load(msp->ms_sm, allocs, SM_ALLOC));
3393 		range_tree_vacate(allocs, range_tree_add, svr->svr_allocd_segs);
3394 	}
3395 	range_tree_destroy(allocs);
3396 
3397 	iterate_through_spacemap_logs(spa, load_unflushed_svr_segs_cb, svr);
3398 
3399 	/*
3400 	 * Clear everything past what has been synced,
3401 	 * because we have not allocated mappings for
3402 	 * it yet.
3403 	 */
3404 	range_tree_clear(svr->svr_allocd_segs,
3405 	    vdev_indirect_mapping_max_offset(vim),
3406 	    vd->vdev_asize - vdev_indirect_mapping_max_offset(vim));
3407 
3408 	zcb->zcb_removing_size += range_tree_space(svr->svr_allocd_segs);
3409 	range_tree_vacate(svr->svr_allocd_segs, claim_segment_cb, vd);
3410 
3411 	spa_config_exit(spa, SCL_CONFIG, FTAG);
3412 }
3413 
3414 /* ARGSUSED */
3415 static int
3416 increment_indirect_mapping_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
3417 {
3418 	zdb_cb_t *zcb = arg;
3419 	spa_t *spa = zcb->zcb_spa;
3420 	vdev_t *vd;
3421 	const dva_t *dva = &bp->blk_dva[0];
3422 
3423 	ASSERT(!dump_opt['L']);
3424 	ASSERT3U(BP_GET_NDVAS(bp), ==, 1);
3425 
3426 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3427 	vd = vdev_lookup_top(zcb->zcb_spa, DVA_GET_VDEV(dva));
3428 	ASSERT3P(vd, !=, NULL);
3429 	spa_config_exit(spa, SCL_VDEV, FTAG);
3430 
3431 	ASSERT(vd->vdev_indirect_config.vic_mapping_object != 0);
3432 	ASSERT3P(zcb->zcb_vd_obsolete_counts[vd->vdev_id], !=, NULL);
3433 
3434 	vdev_indirect_mapping_increment_obsolete_count(
3435 	    vd->vdev_indirect_mapping,
3436 	    DVA_GET_OFFSET(dva), DVA_GET_ASIZE(dva),
3437 	    zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
3438 
3439 	return (0);
3440 }
3441 
3442 static uint32_t *
3443 zdb_load_obsolete_counts(vdev_t *vd)
3444 {
3445 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3446 	spa_t *spa = vd->vdev_spa;
3447 	spa_condensing_indirect_phys_t *scip =
3448 	    &spa->spa_condensing_indirect_phys;
3449 	uint32_t *counts;
3450 
3451 	EQUIV(vdev_obsolete_sm_object(vd) != 0, vd->vdev_obsolete_sm != NULL);
3452 	counts = vdev_indirect_mapping_load_obsolete_counts(vim);
3453 	if (vd->vdev_obsolete_sm != NULL) {
3454 		vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
3455 		    vd->vdev_obsolete_sm);
3456 	}
3457 	if (scip->scip_vdev == vd->vdev_id &&
3458 	    scip->scip_prev_obsolete_sm_object != 0) {
3459 		space_map_t *prev_obsolete_sm = NULL;
3460 		VERIFY0(space_map_open(&prev_obsolete_sm, spa->spa_meta_objset,
3461 		    scip->scip_prev_obsolete_sm_object, 0, vd->vdev_asize, 0));
3462 		vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
3463 		    prev_obsolete_sm);
3464 		space_map_close(prev_obsolete_sm);
3465 	}
3466 	return (counts);
3467 }
3468 
3469 typedef struct checkpoint_sm_exclude_entry_arg {
3470 	vdev_t *cseea_vd;
3471 	uint64_t cseea_checkpoint_size;
3472 } checkpoint_sm_exclude_entry_arg_t;
3473 
3474 static int
3475 checkpoint_sm_exclude_entry_cb(space_map_entry_t *sme, void *arg)
3476 {
3477 	checkpoint_sm_exclude_entry_arg_t *cseea = arg;
3478 	vdev_t *vd = cseea->cseea_vd;
3479 	metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
3480 	uint64_t end = sme->sme_offset + sme->sme_run;
3481 
3482 	ASSERT(sme->sme_type == SM_FREE);
3483 
3484 	/*
3485 	 * Since the vdev_checkpoint_sm exists in the vdev level
3486 	 * and the ms_sm space maps exist in the metaslab level,
3487 	 * an entry in the checkpoint space map could theoretically
3488 	 * cross the boundaries of the metaslab that it belongs.
3489 	 *
3490 	 * In reality, because of the way that we populate and
3491 	 * manipulate the checkpoint's space maps currently,
3492 	 * there shouldn't be any entries that cross metaslabs.
3493 	 * Hence the assertion below.
3494 	 *
3495 	 * That said, there is no fundamental requirement that
3496 	 * the checkpoint's space map entries should not cross
3497 	 * metaslab boundaries. So if needed we could add code
3498 	 * that handles metaslab-crossing segments in the future.
3499 	 */
3500 	VERIFY3U(sme->sme_offset, >=, ms->ms_start);
3501 	VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
3502 
3503 	/*
3504 	 * By removing the entry from the allocated segments we
3505 	 * also verify that the entry is there to begin with.
3506 	 */
3507 	mutex_enter(&ms->ms_lock);
3508 	range_tree_remove(ms->ms_allocatable, sme->sme_offset, sme->sme_run);
3509 	mutex_exit(&ms->ms_lock);
3510 
3511 	cseea->cseea_checkpoint_size += sme->sme_run;
3512 	return (0);
3513 }
3514 
3515 static void
3516 zdb_leak_init_vdev_exclude_checkpoint(vdev_t *vd, zdb_cb_t *zcb)
3517 {
3518 	spa_t *spa = vd->vdev_spa;
3519 	space_map_t *checkpoint_sm = NULL;
3520 	uint64_t checkpoint_sm_obj;
3521 
3522 	/*
3523 	 * If there is no vdev_top_zap, we are in a pool whose
3524 	 * version predates the pool checkpoint feature.
3525 	 */
3526 	if (vd->vdev_top_zap == 0)
3527 		return;
3528 
3529 	/*
3530 	 * If there is no reference of the vdev_checkpoint_sm in
3531 	 * the vdev_top_zap, then one of the following scenarios
3532 	 * is true:
3533 	 *
3534 	 * 1] There is no checkpoint
3535 	 * 2] There is a checkpoint, but no checkpointed blocks
3536 	 *    have been freed yet
3537 	 * 3] The current vdev is indirect
3538 	 *
3539 	 * In these cases we return immediately.
3540 	 */
3541 	if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
3542 	    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
3543 		return;
3544 
3545 	VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
3546 	    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1,
3547 	    &checkpoint_sm_obj));
3548 
3549 	checkpoint_sm_exclude_entry_arg_t cseea;
3550 	cseea.cseea_vd = vd;
3551 	cseea.cseea_checkpoint_size = 0;
3552 
3553 	VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
3554 	    checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
3555 
3556 	VERIFY0(space_map_iterate(checkpoint_sm,
3557 	    space_map_length(checkpoint_sm),
3558 	    checkpoint_sm_exclude_entry_cb, &cseea));
3559 	space_map_close(checkpoint_sm);
3560 
3561 	zcb->zcb_checkpoint_size += cseea.cseea_checkpoint_size;
3562 }
3563 
3564 static void
3565 zdb_leak_init_exclude_checkpoint(spa_t *spa, zdb_cb_t *zcb)
3566 {
3567 	ASSERT(!dump_opt['L']);
3568 
3569 	vdev_t *rvd = spa->spa_root_vdev;
3570 	for (uint64_t c = 0; c < rvd->vdev_children; c++) {
3571 		ASSERT3U(c, ==, rvd->vdev_child[c]->vdev_id);
3572 		zdb_leak_init_vdev_exclude_checkpoint(rvd->vdev_child[c], zcb);
3573 	}
3574 }
3575 
3576 static int
3577 count_unflushed_space_cb(spa_t *spa, space_map_entry_t *sme,
3578     uint64_t txg, void *arg)
3579 {
3580 	int64_t *ualloc_space = arg;
3581 	uint64_t offset = sme->sme_offset;
3582 	uint64_t vdev_id = sme->sme_vdev;
3583 
3584 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
3585 	if (!vdev_is_concrete(vd))
3586 		return (0);
3587 
3588 	metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
3589 	ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
3590 
3591 	if (txg < metaslab_unflushed_txg(ms))
3592 		return (0);
3593 
3594 	if (sme->sme_type == SM_ALLOC)
3595 		*ualloc_space += sme->sme_run;
3596 	else
3597 		*ualloc_space -= sme->sme_run;
3598 
3599 	return (0);
3600 }
3601 
3602 static int64_t
3603 get_unflushed_alloc_space(spa_t *spa)
3604 {
3605 	if (dump_opt['L'])
3606 		return (0);
3607 
3608 	int64_t ualloc_space = 0;
3609 	iterate_through_spacemap_logs(spa, count_unflushed_space_cb,
3610 	    &ualloc_space);
3611 	return (ualloc_space);
3612 }
3613 
3614 static int
3615 load_unflushed_cb(spa_t *spa, space_map_entry_t *sme, uint64_t txg, void *arg)
3616 {
3617 	maptype_t *uic_maptype = arg;
3618 	uint64_t offset = sme->sme_offset;
3619 	uint64_t size = sme->sme_run;
3620 	uint64_t vdev_id = sme->sme_vdev;
3621 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
3622 
3623 	/* skip indirect vdevs */
3624 	if (!vdev_is_concrete(vd))
3625 		return (0);
3626 
3627 	metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
3628 
3629 	ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
3630 	ASSERT(*uic_maptype == SM_ALLOC || *uic_maptype == SM_FREE);
3631 
3632 	if (txg < metaslab_unflushed_txg(ms))
3633 		return (0);
3634 
3635 	if (*uic_maptype == sme->sme_type)
3636 		range_tree_add(ms->ms_allocatable, offset, size);
3637 	else
3638 		range_tree_remove(ms->ms_allocatable, offset, size);
3639 
3640 	return (0);
3641 }
3642 
3643 static void
3644 load_unflushed_to_ms_allocatables(spa_t *spa, maptype_t maptype)
3645 {
3646 	iterate_through_spacemap_logs(spa, load_unflushed_cb, &maptype);
3647 }
3648 
3649 static void
3650 load_concrete_ms_allocatable_trees(spa_t *spa, maptype_t maptype)
3651 {
3652 	vdev_t *rvd = spa->spa_root_vdev;
3653 	for (uint64_t i = 0; i < rvd->vdev_children; i++) {
3654 		vdev_t *vd = rvd->vdev_child[i];
3655 
3656 		ASSERT3U(i, ==, vd->vdev_id);
3657 
3658 		if (vd->vdev_ops == &vdev_indirect_ops)
3659 			continue;
3660 
3661 		for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
3662 			metaslab_t *msp = vd->vdev_ms[m];
3663 
3664 			(void) fprintf(stderr,
3665 			    "\rloading concrete vdev %llu, "
3666 			    "metaslab %llu of %llu ...",
3667 			    (longlong_t)vd->vdev_id,
3668 			    (longlong_t)msp->ms_id,
3669 			    (longlong_t)vd->vdev_ms_count);
3670 
3671 			mutex_enter(&msp->ms_lock);
3672 			range_tree_vacate(msp->ms_allocatable, NULL, NULL);
3673 
3674 			/*
3675 			 * We don't want to spend the CPU manipulating the
3676 			 * size-ordered tree, so clear the range_tree ops.
3677 			 */
3678 			msp->ms_allocatable->rt_ops = NULL;
3679 
3680 			if (msp->ms_sm != NULL) {
3681 				VERIFY0(space_map_load(msp->ms_sm,
3682 				    msp->ms_allocatable, maptype));
3683 			}
3684 			if (!msp->ms_loaded)
3685 				msp->ms_loaded = B_TRUE;
3686 			mutex_exit(&msp->ms_lock);
3687 		}
3688 	}
3689 
3690 	load_unflushed_to_ms_allocatables(spa, maptype);
3691 }
3692 
3693 /*
3694  * vm_idxp is an in-out parameter which (for indirect vdevs) is the
3695  * index in vim_entries that has the first entry in this metaslab.
3696  * On return, it will be set to the first entry after this metaslab.
3697  */
3698 static void
3699 load_indirect_ms_allocatable_tree(vdev_t *vd, metaslab_t *msp,
3700     uint64_t *vim_idxp)
3701 {
3702 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3703 
3704 	mutex_enter(&msp->ms_lock);
3705 	range_tree_vacate(msp->ms_allocatable, NULL, NULL);
3706 
3707 	/*
3708 	 * We don't want to spend the CPU manipulating the
3709 	 * size-ordered tree, so clear the range_tree ops.
3710 	 */
3711 	msp->ms_allocatable->rt_ops = NULL;
3712 
3713 	for (; *vim_idxp < vdev_indirect_mapping_num_entries(vim);
3714 	    (*vim_idxp)++) {
3715 		vdev_indirect_mapping_entry_phys_t *vimep =
3716 		    &vim->vim_entries[*vim_idxp];
3717 		uint64_t ent_offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
3718 		uint64_t ent_len = DVA_GET_ASIZE(&vimep->vimep_dst);
3719 		ASSERT3U(ent_offset, >=, msp->ms_start);
3720 		if (ent_offset >= msp->ms_start + msp->ms_size)
3721 			break;
3722 
3723 		/*
3724 		 * Mappings do not cross metaslab boundaries,
3725 		 * because we create them by walking the metaslabs.
3726 		 */
3727 		ASSERT3U(ent_offset + ent_len, <=,
3728 		    msp->ms_start + msp->ms_size);
3729 		range_tree_add(msp->ms_allocatable, ent_offset, ent_len);
3730 	}
3731 
3732 	if (!msp->ms_loaded)
3733 		msp->ms_loaded = B_TRUE;
3734 	mutex_exit(&msp->ms_lock);
3735 }
3736 
3737 static void
3738 zdb_leak_init_prepare_indirect_vdevs(spa_t *spa, zdb_cb_t *zcb)
3739 {
3740 	ASSERT(!dump_opt['L']);
3741 
3742 	vdev_t *rvd = spa->spa_root_vdev;
3743 	for (uint64_t c = 0; c < rvd->vdev_children; c++) {
3744 		vdev_t *vd = rvd->vdev_child[c];
3745 
3746 		ASSERT3U(c, ==, vd->vdev_id);
3747 
3748 		if (vd->vdev_ops != &vdev_indirect_ops)
3749 			continue;
3750 
3751 		/*
3752 		 * Note: we don't check for mapping leaks on
3753 		 * removing vdevs because their ms_allocatable's
3754 		 * are used to look for leaks in allocated space.
3755 		 */
3756 		zcb->zcb_vd_obsolete_counts[c] = zdb_load_obsolete_counts(vd);
3757 
3758 		/*
3759 		 * Normally, indirect vdevs don't have any
3760 		 * metaslabs.  We want to set them up for
3761 		 * zio_claim().
3762 		 */
3763 		VERIFY0(vdev_metaslab_init(vd, 0));
3764 
3765 		vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3766 		uint64_t vim_idx = 0;
3767 		for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
3768 
3769 			(void) fprintf(stderr,
3770 			    "\rloading indirect vdev %llu, "
3771 			    "metaslab %llu of %llu ...",
3772 			    (longlong_t)vd->vdev_id,
3773 			    (longlong_t)vd->vdev_ms[m]->ms_id,
3774 			    (longlong_t)vd->vdev_ms_count);
3775 
3776 			load_indirect_ms_allocatable_tree(vd, vd->vdev_ms[m],
3777 			    &vim_idx);
3778 		}
3779 		ASSERT3U(vim_idx, ==, vdev_indirect_mapping_num_entries(vim));
3780 	}
3781 }
3782 
3783 static void
3784 zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
3785 {
3786 	zcb->zcb_spa = spa;
3787 
3788 	if (dump_opt['L'])
3789 		return;
3790 
3791 	dsl_pool_t *dp = spa->spa_dsl_pool;
3792 	vdev_t *rvd = spa->spa_root_vdev;
3793 
3794 	/*
3795 	 * We are going to be changing the meaning of the metaslab's
3796 	 * ms_allocatable.  Ensure that the allocator doesn't try to
3797 	 * use the tree.
3798 	 */
3799 	spa->spa_normal_class->mc_ops = &zdb_metaslab_ops;
3800 	spa->spa_log_class->mc_ops = &zdb_metaslab_ops;
3801 
3802 	zcb->zcb_vd_obsolete_counts =
3803 	    umem_zalloc(rvd->vdev_children * sizeof (uint32_t *),
3804 	    UMEM_NOFAIL);
3805 
3806 	/*
3807 	 * For leak detection, we overload the ms_allocatable trees
3808 	 * to contain allocated segments instead of free segments.
3809 	 * As a result, we can't use the normal metaslab_load/unload
3810 	 * interfaces.
3811 	 */
3812 	zdb_leak_init_prepare_indirect_vdevs(spa, zcb);
3813 	load_concrete_ms_allocatable_trees(spa, SM_ALLOC);
3814 
3815 	/*
3816 	 * On load_concrete_ms_allocatable_trees() we loaded all the
3817 	 * allocated entries from the ms_sm to the ms_allocatable for
3818 	 * each metaslab. If the pool has a checkpoint or is in the
3819 	 * middle of discarding a checkpoint, some of these blocks
3820 	 * may have been freed but their ms_sm may not have been
3821 	 * updated because they are referenced by the checkpoint. In
3822 	 * order to avoid false-positives during leak-detection, we
3823 	 * go through the vdev's checkpoint space map and exclude all
3824 	 * its entries from their relevant ms_allocatable.
3825 	 *
3826 	 * We also aggregate the space held by the checkpoint and add
3827 	 * it to zcb_checkpoint_size.
3828 	 *
3829 	 * Note that at this point we are also verifying that all the
3830 	 * entries on the checkpoint_sm are marked as allocated in
3831 	 * the ms_sm of their relevant metaslab.
3832 	 * [see comment in checkpoint_sm_exclude_entry_cb()]
3833 	 */
3834 	zdb_leak_init_exclude_checkpoint(spa, zcb);
3835 	ASSERT3U(zcb->zcb_checkpoint_size, ==, spa_get_checkpoint_space(spa));
3836 
3837 	/* for cleaner progress output */
3838 	(void) fprintf(stderr, "\n");
3839 
3840 	if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
3841 		ASSERT(spa_feature_is_enabled(spa,
3842 		    SPA_FEATURE_DEVICE_REMOVAL));
3843 		(void) bpobj_iterate_nofree(&dp->dp_obsolete_bpobj,
3844 		    increment_indirect_mapping_cb, zcb, NULL);
3845 	}
3846 
3847 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3848 	zdb_ddt_leak_init(spa, zcb);
3849 	spa_config_exit(spa, SCL_CONFIG, FTAG);
3850 }
3851 
3852 static boolean_t
3853 zdb_check_for_obsolete_leaks(vdev_t *vd, zdb_cb_t *zcb)
3854 {
3855 	boolean_t leaks = B_FALSE;
3856 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3857 	uint64_t total_leaked = 0;
3858 
3859 	ASSERT(vim != NULL);
3860 
3861 	for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
3862 		vdev_indirect_mapping_entry_phys_t *vimep =
3863 		    &vim->vim_entries[i];
3864 		uint64_t obsolete_bytes = 0;
3865 		uint64_t offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
3866 		metaslab_t *msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
3867 
3868 		/*
3869 		 * This is not very efficient but it's easy to
3870 		 * verify correctness.
3871 		 */
3872 		for (uint64_t inner_offset = 0;
3873 		    inner_offset < DVA_GET_ASIZE(&vimep->vimep_dst);
3874 		    inner_offset += 1 << vd->vdev_ashift) {
3875 			if (range_tree_contains(msp->ms_allocatable,
3876 			    offset + inner_offset, 1 << vd->vdev_ashift)) {
3877 				obsolete_bytes += 1 << vd->vdev_ashift;
3878 			}
3879 		}
3880 
3881 		int64_t bytes_leaked = obsolete_bytes -
3882 		    zcb->zcb_vd_obsolete_counts[vd->vdev_id][i];
3883 		ASSERT3U(DVA_GET_ASIZE(&vimep->vimep_dst), >=,
3884 		    zcb->zcb_vd_obsolete_counts[vd->vdev_id][i]);
3885 		if (bytes_leaked != 0 &&
3886 		    (vdev_obsolete_counts_are_precise(vd) ||
3887 		    dump_opt['d'] >= 5)) {
3888 			(void) printf("obsolete indirect mapping count "
3889 			    "mismatch on %llu:%llx:%llx : %llx bytes leaked\n",
3890 			    (u_longlong_t)vd->vdev_id,
3891 			    (u_longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
3892 			    (u_longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
3893 			    (u_longlong_t)bytes_leaked);
3894 		}
3895 		total_leaked += ABS(bytes_leaked);
3896 	}
3897 
3898 	if (!vdev_obsolete_counts_are_precise(vd) && total_leaked > 0) {
3899 		int pct_leaked = total_leaked * 100 /
3900 		    vdev_indirect_mapping_bytes_mapped(vim);
3901 		(void) printf("cannot verify obsolete indirect mapping "
3902 		    "counts of vdev %llu because precise feature was not "
3903 		    "enabled when it was removed: %d%% (%llx bytes) of mapping"
3904 		    "unreferenced\n",
3905 		    (u_longlong_t)vd->vdev_id, pct_leaked,
3906 		    (u_longlong_t)total_leaked);
3907 	} else if (total_leaked > 0) {
3908 		(void) printf("obsolete indirect mapping count mismatch "
3909 		    "for vdev %llu -- %llx total bytes mismatched\n",
3910 		    (u_longlong_t)vd->vdev_id,
3911 		    (u_longlong_t)total_leaked);
3912 		leaks |= B_TRUE;
3913 	}
3914 
3915 	vdev_indirect_mapping_free_obsolete_counts(vim,
3916 	    zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
3917 	zcb->zcb_vd_obsolete_counts[vd->vdev_id] = NULL;
3918 
3919 	return (leaks);
3920 }
3921 
3922 static boolean_t
3923 zdb_leak_fini(spa_t *spa, zdb_cb_t *zcb)
3924 {
3925 	if (dump_opt['L'])
3926 		return (B_FALSE);
3927 
3928 	boolean_t leaks = B_FALSE;
3929 
3930 	vdev_t *rvd = spa->spa_root_vdev;
3931 	for (unsigned c = 0; c < rvd->vdev_children; c++) {
3932 		vdev_t *vd = rvd->vdev_child[c];
3933 #if DEBUG
3934 		metaslab_group_t *mg = vd->vdev_mg;
3935 #endif
3936 
3937 		if (zcb->zcb_vd_obsolete_counts[c] != NULL) {
3938 			leaks |= zdb_check_for_obsolete_leaks(vd, zcb);
3939 		}
3940 
3941 		for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
3942 			metaslab_t *msp = vd->vdev_ms[m];
3943 			ASSERT3P(mg, ==, msp->ms_group);
3944 
3945 			/*
3946 			 * ms_allocatable has been overloaded
3947 			 * to contain allocated segments. Now that
3948 			 * we finished traversing all blocks, any
3949 			 * block that remains in the ms_allocatable
3950 			 * represents an allocated block that we
3951 			 * did not claim during the traversal.
3952 			 * Claimed blocks would have been removed
3953 			 * from the ms_allocatable.  For indirect
3954 			 * vdevs, space remaining in the tree
3955 			 * represents parts of the mapping that are
3956 			 * not referenced, which is not a bug.
3957 			 */
3958 			if (vd->vdev_ops == &vdev_indirect_ops) {
3959 				range_tree_vacate(msp->ms_allocatable,
3960 				    NULL, NULL);
3961 			} else {
3962 				range_tree_vacate(msp->ms_allocatable,
3963 				    zdb_leak, vd);
3964 			}
3965 			if (msp->ms_loaded) {
3966 				msp->ms_loaded = B_FALSE;
3967 			}
3968 		}
3969 
3970 	}
3971 
3972 	umem_free(zcb->zcb_vd_obsolete_counts,
3973 	    rvd->vdev_children * sizeof (uint32_t *));
3974 	zcb->zcb_vd_obsolete_counts = NULL;
3975 
3976 	return (leaks);
3977 }
3978 
3979 /* ARGSUSED */
3980 static int
3981 count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
3982 {
3983 	zdb_cb_t *zcb = arg;
3984 
3985 	if (dump_opt['b'] >= 5) {
3986 		char blkbuf[BP_SPRINTF_LEN];
3987 		snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
3988 		(void) printf("[%s] %s\n",
3989 		    "deferred free", blkbuf);
3990 	}
3991 	zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
3992 	return (0);
3993 }
3994 
3995 static int
3996 dump_block_stats(spa_t *spa)
3997 {
3998 	zdb_cb_t zcb;
3999 	zdb_blkstats_t *zb, *tzb;
4000 	uint64_t norm_alloc, norm_space, total_alloc, total_found;
4001 	int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
4002 	    TRAVERSE_NO_DECRYPT | TRAVERSE_HARD;
4003 	boolean_t leaks = B_FALSE;
4004 	int err;
4005 
4006 	bzero(&zcb, sizeof (zcb));
4007 	(void) printf("\nTraversing all blocks %s%s%s%s%s...\n\n",
4008 	    (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
4009 	    (dump_opt['c'] == 1) ? "metadata " : "",
4010 	    dump_opt['c'] ? "checksums " : "",
4011 	    (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
4012 	    !dump_opt['L'] ? "nothing leaked " : "");
4013 
4014 	/*
4015 	 * When leak detection is enabled we load all space maps as SM_ALLOC
4016 	 * maps, then traverse the pool claiming each block we discover. If
4017 	 * the pool is perfectly consistent, the segment trees will be empty
4018 	 * when we're done. Anything left over is a leak; any block we can't
4019 	 * claim (because it's not part of any space map) is a double
4020 	 * allocation, reference to a freed block, or an unclaimed log block.
4021 	 *
4022 	 * When leak detection is disabled (-L option) we still traverse the
4023 	 * pool claiming each block we discover, but we skip opening any space
4024 	 * maps.
4025 	 */
4026 	bzero(&zcb, sizeof (zdb_cb_t));
4027 	zdb_leak_init(spa, &zcb);
4028 
4029 	/*
4030 	 * If there's a deferred-free bplist, process that first.
4031 	 */
4032 	(void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
4033 	    count_block_cb, &zcb, NULL);
4034 
4035 	if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
4036 		(void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
4037 		    count_block_cb, &zcb, NULL);
4038 	}
4039 
4040 	zdb_claim_removing(spa, &zcb);
4041 
4042 	if (spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
4043 		VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
4044 		    spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
4045 		    &zcb, NULL));
4046 	}
4047 
4048 	if (dump_opt['c'] > 1)
4049 		flags |= TRAVERSE_PREFETCH_DATA;
4050 
4051 	zcb.zcb_totalasize = metaslab_class_get_alloc(spa_normal_class(spa));
4052 	zcb.zcb_totalasize += metaslab_class_get_alloc(spa_special_class(spa));
4053 	zcb.zcb_totalasize += metaslab_class_get_alloc(spa_dedup_class(spa));
4054 	zcb.zcb_start = zcb.zcb_lastprint = gethrtime();
4055 	err = traverse_pool(spa, 0, flags, zdb_blkptr_cb, &zcb);
4056 
4057 	/*
4058 	 * If we've traversed the data blocks then we need to wait for those
4059 	 * I/Os to complete. We leverage "The Godfather" zio to wait on
4060 	 * all async I/Os to complete.
4061 	 */
4062 	if (dump_opt['c']) {
4063 		for (int i = 0; i < max_ncpus; i++) {
4064 			(void) zio_wait(spa->spa_async_zio_root[i]);
4065 			spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
4066 			    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
4067 			    ZIO_FLAG_GODFATHER);
4068 		}
4069 	}
4070 
4071 	/*
4072 	 * Done after zio_wait() since zcb_haderrors is modified in
4073 	 * zdb_blkptr_done()
4074 	 */
4075 	zcb.zcb_haderrors |= err;
4076 
4077 	if (zcb.zcb_haderrors) {
4078 		(void) printf("\nError counts:\n\n");
4079 		(void) printf("\t%5s  %s\n", "errno", "count");
4080 		for (int e = 0; e < 256; e++) {
4081 			if (zcb.zcb_errors[e] != 0) {
4082 				(void) printf("\t%5d  %llu\n",
4083 				    e, (u_longlong_t)zcb.zcb_errors[e]);
4084 			}
4085 		}
4086 	}
4087 
4088 	/*
4089 	 * Report any leaked segments.
4090 	 */
4091 	leaks |= zdb_leak_fini(spa, &zcb);
4092 
4093 	tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
4094 
4095 	norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
4096 	norm_space = metaslab_class_get_space(spa_normal_class(spa));
4097 
4098 	total_alloc = norm_alloc +
4099 	    metaslab_class_get_alloc(spa_log_class(spa)) +
4100 	    metaslab_class_get_alloc(spa_special_class(spa)) +
4101 	    metaslab_class_get_alloc(spa_dedup_class(spa)) +
4102 	    get_unflushed_alloc_space(spa);
4103 	total_found = tzb->zb_asize - zcb.zcb_dedup_asize +
4104 	    zcb.zcb_removing_size + zcb.zcb_checkpoint_size;
4105 
4106 	if (total_found == total_alloc && !dump_opt['L']) {
4107 		(void) printf("\n\tNo leaks (block sum matches space"
4108 		    " maps exactly)\n");
4109 	} else if (!dump_opt['L']) {
4110 		(void) printf("block traversal size %llu != alloc %llu "
4111 		    "(%s %lld)\n",
4112 		    (u_longlong_t)total_found,
4113 		    (u_longlong_t)total_alloc,
4114 		    (dump_opt['L']) ? "unreachable" : "leaked",
4115 		    (longlong_t)(total_alloc - total_found));
4116 		leaks = B_TRUE;
4117 	}
4118 
4119 	if (tzb->zb_count == 0)
4120 		return (2);
4121 
4122 	(void) printf("\n");
4123 	(void) printf("\t%-16s %14llu\n", "bp count:",
4124 	    (u_longlong_t)tzb->zb_count);
4125 	(void) printf("\t%-16s %14llu\n", "ganged count:",
4126 	    (longlong_t)tzb->zb_gangs);
4127 	(void) printf("\t%-16s %14llu      avg: %6llu\n", "bp logical:",
4128 	    (u_longlong_t)tzb->zb_lsize,
4129 	    (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
4130 	(void) printf("\t%-16s %14llu      avg: %6llu     compression: %6.2f\n",
4131 	    "bp physical:", (u_longlong_t)tzb->zb_psize,
4132 	    (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
4133 	    (double)tzb->zb_lsize / tzb->zb_psize);
4134 	(void) printf("\t%-16s %14llu      avg: %6llu     compression: %6.2f\n",
4135 	    "bp allocated:", (u_longlong_t)tzb->zb_asize,
4136 	    (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
4137 	    (double)tzb->zb_lsize / tzb->zb_asize);
4138 	(void) printf("\t%-16s %14llu    ref>1: %6llu   deduplication: %6.2f\n",
4139 	    "bp deduped:", (u_longlong_t)zcb.zcb_dedup_asize,
4140 	    (u_longlong_t)zcb.zcb_dedup_blocks,
4141 	    (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
4142 	(void) printf("\t%-16s %14llu     used: %5.2f%%\n", "Normal class:",
4143 	    (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
4144 
4145 	if (spa_special_class(spa)->mc_rotor != NULL) {
4146 		uint64_t alloc = metaslab_class_get_alloc(
4147 		    spa_special_class(spa));
4148 		uint64_t space = metaslab_class_get_space(
4149 		    spa_special_class(spa));
4150 
4151 		(void) printf("\t%-16s %14llu     used: %5.2f%%\n",
4152 		    "Special class", (u_longlong_t)alloc,
4153 		    100.0 * alloc / space);
4154 	}
4155 
4156 	if (spa_dedup_class(spa)->mc_rotor != NULL) {
4157 		uint64_t alloc = metaslab_class_get_alloc(
4158 		    spa_dedup_class(spa));
4159 		uint64_t space = metaslab_class_get_space(
4160 		    spa_dedup_class(spa));
4161 
4162 		(void) printf("\t%-16s %14llu     used: %5.2f%%\n",
4163 		    "Dedup class", (u_longlong_t)alloc,
4164 		    100.0 * alloc / space);
4165 	}
4166 
4167 	for (bp_embedded_type_t i = 0; i < NUM_BP_EMBEDDED_TYPES; i++) {
4168 		if (zcb.zcb_embedded_blocks[i] == 0)
4169 			continue;
4170 		(void) printf("\n");
4171 		(void) printf("\tadditional, non-pointer bps of type %u: "
4172 		    "%10llu\n",
4173 		    i, (u_longlong_t)zcb.zcb_embedded_blocks[i]);
4174 
4175 		if (dump_opt['b'] >= 3) {
4176 			(void) printf("\t number of (compressed) bytes:  "
4177 			    "number of bps\n");
4178 			dump_histogram(zcb.zcb_embedded_histogram[i],
4179 			    sizeof (zcb.zcb_embedded_histogram[i]) /
4180 			    sizeof (zcb.zcb_embedded_histogram[i][0]), 0);
4181 		}
4182 	}
4183 
4184 	if (tzb->zb_ditto_samevdev != 0) {
4185 		(void) printf("\tDittoed blocks on same vdev: %llu\n",
4186 		    (longlong_t)tzb->zb_ditto_samevdev);
4187 	}
4188 	if (tzb->zb_ditto_same_ms != 0) {
4189 		(void) printf("\tDittoed blocks in same metaslab: %llu\n",
4190 		    (longlong_t)tzb->zb_ditto_same_ms);
4191 	}
4192 
4193 	for (uint64_t v = 0; v < spa->spa_root_vdev->vdev_children; v++) {
4194 		vdev_t *vd = spa->spa_root_vdev->vdev_child[v];
4195 		vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
4196 
4197 		if (vim == NULL) {
4198 			continue;
4199 		}
4200 
4201 		char mem[32];
4202 		zdb_nicenum(vdev_indirect_mapping_num_entries(vim),
4203 		    mem, vdev_indirect_mapping_size(vim));
4204 
4205 		(void) printf("\tindirect vdev id %llu has %llu segments "
4206 		    "(%s in memory)\n",
4207 		    (longlong_t)vd->vdev_id,
4208 		    (longlong_t)vdev_indirect_mapping_num_entries(vim), mem);
4209 	}
4210 
4211 	if (dump_opt['b'] >= 2) {
4212 		int l, t, level;
4213 		(void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
4214 		    "\t  avg\t comp\t%%Total\tType\n");
4215 
4216 		for (t = 0; t <= ZDB_OT_TOTAL; t++) {
4217 			char csize[32], lsize[32], psize[32], asize[32];
4218 			char avg[32], gang[32];
4219 			const char *typename;
4220 
4221 			/* make sure nicenum has enough space */
4222 			CTASSERT(sizeof (csize) >= NN_NUMBUF_SZ);
4223 			CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
4224 			CTASSERT(sizeof (psize) >= NN_NUMBUF_SZ);
4225 			CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
4226 			CTASSERT(sizeof (avg) >= NN_NUMBUF_SZ);
4227 			CTASSERT(sizeof (gang) >= NN_NUMBUF_SZ);
4228 
4229 			if (t < DMU_OT_NUMTYPES)
4230 				typename = dmu_ot[t].ot_name;
4231 			else
4232 				typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
4233 
4234 			if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
4235 				(void) printf("%6s\t%5s\t%5s\t%5s"
4236 				    "\t%5s\t%5s\t%6s\t%s\n",
4237 				    "-",
4238 				    "-",
4239 				    "-",
4240 				    "-",
4241 				    "-",
4242 				    "-",
4243 				    "-",
4244 				    typename);
4245 				continue;
4246 			}
4247 
4248 			for (l = ZB_TOTAL - 1; l >= -1; l--) {
4249 				level = (l == -1 ? ZB_TOTAL : l);
4250 				zb = &zcb.zcb_type[level][t];
4251 
4252 				if (zb->zb_asize == 0)
4253 					continue;
4254 
4255 				if (dump_opt['b'] < 3 && level != ZB_TOTAL)
4256 					continue;
4257 
4258 				if (level == 0 && zb->zb_asize ==
4259 				    zcb.zcb_type[ZB_TOTAL][t].zb_asize)
4260 					continue;
4261 
4262 				zdb_nicenum(zb->zb_count, csize,
4263 				    sizeof (csize));
4264 				zdb_nicenum(zb->zb_lsize, lsize,
4265 				    sizeof (lsize));
4266 				zdb_nicenum(zb->zb_psize, psize,
4267 				    sizeof (psize));
4268 				zdb_nicenum(zb->zb_asize, asize,
4269 				    sizeof (asize));
4270 				zdb_nicenum(zb->zb_asize / zb->zb_count, avg,
4271 				    sizeof (avg));
4272 				zdb_nicenum(zb->zb_gangs, gang, sizeof (gang));
4273 
4274 				(void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
4275 				    "\t%5.2f\t%6.2f\t",
4276 				    csize, lsize, psize, asize, avg,
4277 				    (double)zb->zb_lsize / zb->zb_psize,
4278 				    100.0 * zb->zb_asize / tzb->zb_asize);
4279 
4280 				if (level == ZB_TOTAL)
4281 					(void) printf("%s\n", typename);
4282 				else
4283 					(void) printf("    L%d %s\n",
4284 					    level, typename);
4285 
4286 				if (dump_opt['b'] >= 3 && zb->zb_gangs > 0) {
4287 					(void) printf("\t number of ganged "
4288 					    "blocks: %s\n", gang);
4289 				}
4290 
4291 				if (dump_opt['b'] >= 4) {
4292 					(void) printf("psize "
4293 					    "(in 512-byte sectors): "
4294 					    "number of blocks\n");
4295 					dump_histogram(zb->zb_psize_histogram,
4296 					    PSIZE_HISTO_SIZE, 0);
4297 				}
4298 			}
4299 		}
4300 	}
4301 
4302 	(void) printf("\n");
4303 
4304 	if (leaks)
4305 		return (2);
4306 
4307 	if (zcb.zcb_haderrors)
4308 		return (3);
4309 
4310 	return (0);
4311 }
4312 
4313 typedef struct zdb_ddt_entry {
4314 	ddt_key_t	zdde_key;
4315 	uint64_t	zdde_ref_blocks;
4316 	uint64_t	zdde_ref_lsize;
4317 	uint64_t	zdde_ref_psize;
4318 	uint64_t	zdde_ref_dsize;
4319 	avl_node_t	zdde_node;
4320 } zdb_ddt_entry_t;
4321 
4322 /* ARGSUSED */
4323 static int
4324 zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
4325     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
4326 {
4327 	avl_tree_t *t = arg;
4328 	avl_index_t where;
4329 	zdb_ddt_entry_t *zdde, zdde_search;
4330 
4331 	if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
4332 		return (0);
4333 
4334 	if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
4335 		(void) printf("traversing objset %llu, %llu objects, "
4336 		    "%lu blocks so far\n",
4337 		    (u_longlong_t)zb->zb_objset,
4338 		    (u_longlong_t)BP_GET_FILL(bp),
4339 		    avl_numnodes(t));
4340 	}
4341 
4342 	if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
4343 	    BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
4344 		return (0);
4345 
4346 	ddt_key_fill(&zdde_search.zdde_key, bp);
4347 
4348 	zdde = avl_find(t, &zdde_search, &where);
4349 
4350 	if (zdde == NULL) {
4351 		zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
4352 		zdde->zdde_key = zdde_search.zdde_key;
4353 		avl_insert(t, zdde, where);
4354 	}
4355 
4356 	zdde->zdde_ref_blocks += 1;
4357 	zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
4358 	zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
4359 	zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
4360 
4361 	return (0);
4362 }
4363 
4364 static void
4365 dump_simulated_ddt(spa_t *spa)
4366 {
4367 	avl_tree_t t;
4368 	void *cookie = NULL;
4369 	zdb_ddt_entry_t *zdde;
4370 	ddt_histogram_t ddh_total;
4371 	ddt_stat_t dds_total;
4372 
4373 	bzero(&ddh_total, sizeof (ddh_total));
4374 	bzero(&dds_total, sizeof (dds_total));
4375 	avl_create(&t, ddt_entry_compare,
4376 	    sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
4377 
4378 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4379 
4380 	(void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
4381 	    TRAVERSE_NO_DECRYPT, zdb_ddt_add_cb, &t);
4382 
4383 	spa_config_exit(spa, SCL_CONFIG, FTAG);
4384 
4385 	while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
4386 		ddt_stat_t dds;
4387 		uint64_t refcnt = zdde->zdde_ref_blocks;
4388 		ASSERT(refcnt != 0);
4389 
4390 		dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
4391 		dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
4392 		dds.dds_psize = zdde->zdde_ref_psize / refcnt;
4393 		dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
4394 
4395 		dds.dds_ref_blocks = zdde->zdde_ref_blocks;
4396 		dds.dds_ref_lsize = zdde->zdde_ref_lsize;
4397 		dds.dds_ref_psize = zdde->zdde_ref_psize;
4398 		dds.dds_ref_dsize = zdde->zdde_ref_dsize;
4399 
4400 		ddt_stat_add(&ddh_total.ddh_stat[highbit64(refcnt) - 1],
4401 		    &dds, 0);
4402 
4403 		umem_free(zdde, sizeof (*zdde));
4404 	}
4405 
4406 	avl_destroy(&t);
4407 
4408 	ddt_histogram_stat(&dds_total, &ddh_total);
4409 
4410 	(void) printf("Simulated DDT histogram:\n");
4411 
4412 	zpool_dump_ddt(&dds_total, &ddh_total);
4413 
4414 	dump_dedup_ratio(&dds_total);
4415 }
4416 
4417 static int
4418 verify_device_removal_feature_counts(spa_t *spa)
4419 {
4420 	uint64_t dr_feature_refcount = 0;
4421 	uint64_t oc_feature_refcount = 0;
4422 	uint64_t indirect_vdev_count = 0;
4423 	uint64_t precise_vdev_count = 0;
4424 	uint64_t obsolete_counts_object_count = 0;
4425 	uint64_t obsolete_sm_count = 0;
4426 	uint64_t obsolete_counts_count = 0;
4427 	uint64_t scip_count = 0;
4428 	uint64_t obsolete_bpobj_count = 0;
4429 	int ret = 0;
4430 
4431 	spa_condensing_indirect_phys_t *scip =
4432 	    &spa->spa_condensing_indirect_phys;
4433 	if (scip->scip_next_mapping_object != 0) {
4434 		vdev_t *vd = spa->spa_root_vdev->vdev_child[scip->scip_vdev];
4435 		ASSERT(scip->scip_prev_obsolete_sm_object != 0);
4436 		ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
4437 
4438 		(void) printf("Condensing indirect vdev %llu: new mapping "
4439 		    "object %llu, prev obsolete sm %llu\n",
4440 		    (u_longlong_t)scip->scip_vdev,
4441 		    (u_longlong_t)scip->scip_next_mapping_object,
4442 		    (u_longlong_t)scip->scip_prev_obsolete_sm_object);
4443 		if (scip->scip_prev_obsolete_sm_object != 0) {
4444 			space_map_t *prev_obsolete_sm = NULL;
4445 			VERIFY0(space_map_open(&prev_obsolete_sm,
4446 			    spa->spa_meta_objset,
4447 			    scip->scip_prev_obsolete_sm_object,
4448 			    0, vd->vdev_asize, 0));
4449 			dump_spacemap(spa->spa_meta_objset, prev_obsolete_sm);
4450 			(void) printf("\n");
4451 			space_map_close(prev_obsolete_sm);
4452 		}
4453 
4454 		scip_count += 2;
4455 	}
4456 
4457 	for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
4458 		vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
4459 		vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
4460 
4461 		if (vic->vic_mapping_object != 0) {
4462 			ASSERT(vd->vdev_ops == &vdev_indirect_ops ||
4463 			    vd->vdev_removing);
4464 			indirect_vdev_count++;
4465 
4466 			if (vd->vdev_indirect_mapping->vim_havecounts) {
4467 				obsolete_counts_count++;
4468 			}
4469 		}
4470 		if (vdev_obsolete_counts_are_precise(vd)) {
4471 			ASSERT(vic->vic_mapping_object != 0);
4472 			precise_vdev_count++;
4473 		}
4474 		if (vdev_obsolete_sm_object(vd) != 0) {
4475 			ASSERT(vic->vic_mapping_object != 0);
4476 			obsolete_sm_count++;
4477 		}
4478 	}
4479 
4480 	(void) feature_get_refcount(spa,
4481 	    &spa_feature_table[SPA_FEATURE_DEVICE_REMOVAL],
4482 	    &dr_feature_refcount);
4483 	(void) feature_get_refcount(spa,
4484 	    &spa_feature_table[SPA_FEATURE_OBSOLETE_COUNTS],
4485 	    &oc_feature_refcount);
4486 
4487 	if (dr_feature_refcount != indirect_vdev_count) {
4488 		ret = 1;
4489 		(void) printf("Number of indirect vdevs (%llu) " \
4490 		    "does not match feature count (%llu)\n",
4491 		    (u_longlong_t)indirect_vdev_count,
4492 		    (u_longlong_t)dr_feature_refcount);
4493 	} else {
4494 		(void) printf("Verified device_removal feature refcount " \
4495 		    "of %llu is correct\n",
4496 		    (u_longlong_t)dr_feature_refcount);
4497 	}
4498 
4499 	if (zap_contains(spa_meta_objset(spa), DMU_POOL_DIRECTORY_OBJECT,
4500 	    DMU_POOL_OBSOLETE_BPOBJ) == 0) {
4501 		obsolete_bpobj_count++;
4502 	}
4503 
4504 
4505 	obsolete_counts_object_count = precise_vdev_count;
4506 	obsolete_counts_object_count += obsolete_sm_count;
4507 	obsolete_counts_object_count += obsolete_counts_count;
4508 	obsolete_counts_object_count += scip_count;
4509 	obsolete_counts_object_count += obsolete_bpobj_count;
4510 	obsolete_counts_object_count += remap_deadlist_count;
4511 
4512 	if (oc_feature_refcount != obsolete_counts_object_count) {
4513 		ret = 1;
4514 		(void) printf("Number of obsolete counts objects (%llu) " \
4515 		    "does not match feature count (%llu)\n",
4516 		    (u_longlong_t)obsolete_counts_object_count,
4517 		    (u_longlong_t)oc_feature_refcount);
4518 		(void) printf("pv:%llu os:%llu oc:%llu sc:%llu "
4519 		    "ob:%llu rd:%llu\n",
4520 		    (u_longlong_t)precise_vdev_count,
4521 		    (u_longlong_t)obsolete_sm_count,
4522 		    (u_longlong_t)obsolete_counts_count,
4523 		    (u_longlong_t)scip_count,
4524 		    (u_longlong_t)obsolete_bpobj_count,
4525 		    (u_longlong_t)remap_deadlist_count);
4526 	} else {
4527 		(void) printf("Verified indirect_refcount feature refcount " \
4528 		    "of %llu is correct\n",
4529 		    (u_longlong_t)oc_feature_refcount);
4530 	}
4531 	return (ret);
4532 }
4533 
4534 static void
4535 zdb_set_skip_mmp(char *target)
4536 {
4537 	spa_t *spa;
4538 
4539 	/*
4540 	 * Disable the activity check to allow examination of
4541 	 * active pools.
4542 	 */
4543 	mutex_enter(&spa_namespace_lock);
4544 	if ((spa = spa_lookup(target)) != NULL) {
4545 		spa->spa_import_flags |= ZFS_IMPORT_SKIP_MMP;
4546 	}
4547 	mutex_exit(&spa_namespace_lock);
4548 }
4549 
4550 #define	BOGUS_SUFFIX "_CHECKPOINTED_UNIVERSE"
4551 /*
4552  * Import the checkpointed state of the pool specified by the target
4553  * parameter as readonly. The function also accepts a pool config
4554  * as an optional parameter, else it attempts to infer the config by
4555  * the name of the target pool.
4556  *
4557  * Note that the checkpointed state's pool name will be the name of
4558  * the original pool with the above suffix appened to it. In addition,
4559  * if the target is not a pool name (e.g. a path to a dataset) then
4560  * the new_path parameter is populated with the updated path to
4561  * reflect the fact that we are looking into the checkpointed state.
4562  *
4563  * The function returns a newly-allocated copy of the name of the
4564  * pool containing the checkpointed state. When this copy is no
4565  * longer needed it should be freed with free(3C). Same thing
4566  * applies to the new_path parameter if allocated.
4567  */
4568 static char *
4569 import_checkpointed_state(char *target, nvlist_t *cfg, char **new_path)
4570 {
4571 	int error = 0;
4572 	char *poolname, *bogus_name;
4573 
4574 	/* If the target is not a pool, the extract the pool name */
4575 	char *path_start = strchr(target, '/');
4576 	if (path_start != NULL) {
4577 		size_t poolname_len = path_start - target;
4578 		poolname = strndup(target, poolname_len);
4579 	} else {
4580 		poolname = target;
4581 	}
4582 
4583 	if (cfg == NULL) {
4584 		zdb_set_skip_mmp(poolname);
4585 		error = spa_get_stats(poolname, &cfg, NULL, 0);
4586 		if (error != 0) {
4587 			fatal("Tried to read config of pool \"%s\" but "
4588 			    "spa_get_stats() failed with error %d\n",
4589 			    poolname, error);
4590 		}
4591 	}
4592 
4593 	(void) asprintf(&bogus_name, "%s%s", poolname, BOGUS_SUFFIX);
4594 	fnvlist_add_string(cfg, ZPOOL_CONFIG_POOL_NAME, bogus_name);
4595 
4596 	error = spa_import(bogus_name, cfg, NULL,
4597 	    ZFS_IMPORT_MISSING_LOG | ZFS_IMPORT_CHECKPOINT |
4598 	    ZFS_IMPORT_SKIP_MMP);
4599 	if (error != 0) {
4600 		fatal("Tried to import pool \"%s\" but spa_import() failed "
4601 		    "with error %d\n", bogus_name, error);
4602 	}
4603 
4604 	if (new_path != NULL && path_start != NULL)
4605 		(void) asprintf(new_path, "%s%s", bogus_name, path_start);
4606 
4607 	if (target != poolname)
4608 		free(poolname);
4609 
4610 	return (bogus_name);
4611 }
4612 
4613 typedef struct verify_checkpoint_sm_entry_cb_arg {
4614 	vdev_t *vcsec_vd;
4615 
4616 	/* the following fields are only used for printing progress */
4617 	uint64_t vcsec_entryid;
4618 	uint64_t vcsec_num_entries;
4619 } verify_checkpoint_sm_entry_cb_arg_t;
4620 
4621 #define	ENTRIES_PER_PROGRESS_UPDATE 10000
4622 
4623 static int
4624 verify_checkpoint_sm_entry_cb(space_map_entry_t *sme, void *arg)
4625 {
4626 	verify_checkpoint_sm_entry_cb_arg_t *vcsec = arg;
4627 	vdev_t *vd = vcsec->vcsec_vd;
4628 	metaslab_t *ms = vd->vdev_ms[sme->sme_offset >> vd->vdev_ms_shift];
4629 	uint64_t end = sme->sme_offset + sme->sme_run;
4630 
4631 	ASSERT(sme->sme_type == SM_FREE);
4632 
4633 	if ((vcsec->vcsec_entryid % ENTRIES_PER_PROGRESS_UPDATE) == 0) {
4634 		(void) fprintf(stderr,
4635 		    "\rverifying vdev %llu, space map entry %llu of %llu ...",
4636 		    (longlong_t)vd->vdev_id,
4637 		    (longlong_t)vcsec->vcsec_entryid,
4638 		    (longlong_t)vcsec->vcsec_num_entries);
4639 	}
4640 	vcsec->vcsec_entryid++;
4641 
4642 	/*
4643 	 * See comment in checkpoint_sm_exclude_entry_cb()
4644 	 */
4645 	VERIFY3U(sme->sme_offset, >=, ms->ms_start);
4646 	VERIFY3U(end, <=, ms->ms_start + ms->ms_size);
4647 
4648 	/*
4649 	 * The entries in the vdev_checkpoint_sm should be marked as
4650 	 * allocated in the checkpointed state of the pool, therefore
4651 	 * their respective ms_allocateable trees should not contain them.
4652 	 */
4653 	mutex_enter(&ms->ms_lock);
4654 	range_tree_verify_not_present(ms->ms_allocatable,
4655 	    sme->sme_offset, sme->sme_run);
4656 	mutex_exit(&ms->ms_lock);
4657 
4658 	return (0);
4659 }
4660 
4661 /*
4662  * Verify that all segments in the vdev_checkpoint_sm are allocated
4663  * according to the checkpoint's ms_sm (i.e. are not in the checkpoint's
4664  * ms_allocatable).
4665  *
4666  * Do so by comparing the checkpoint space maps (vdev_checkpoint_sm) of
4667  * each vdev in the current state of the pool to the metaslab space maps
4668  * (ms_sm) of the checkpointed state of the pool.
4669  *
4670  * Note that the function changes the state of the ms_allocatable
4671  * trees of the current spa_t. The entries of these ms_allocatable
4672  * trees are cleared out and then repopulated from with the free
4673  * entries of their respective ms_sm space maps.
4674  */
4675 static void
4676 verify_checkpoint_vdev_spacemaps(spa_t *checkpoint, spa_t *current)
4677 {
4678 	vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
4679 	vdev_t *current_rvd = current->spa_root_vdev;
4680 
4681 	load_concrete_ms_allocatable_trees(checkpoint, SM_FREE);
4682 
4683 	for (uint64_t c = 0; c < ckpoint_rvd->vdev_children; c++) {
4684 		vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[c];
4685 		vdev_t *current_vd = current_rvd->vdev_child[c];
4686 
4687 		space_map_t *checkpoint_sm = NULL;
4688 		uint64_t checkpoint_sm_obj;
4689 
4690 		if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
4691 			/*
4692 			 * Since we don't allow device removal in a pool
4693 			 * that has a checkpoint, we expect that all removed
4694 			 * vdevs were removed from the pool before the
4695 			 * checkpoint.
4696 			 */
4697 			ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
4698 			continue;
4699 		}
4700 
4701 		/*
4702 		 * If the checkpoint space map doesn't exist, then nothing
4703 		 * here is checkpointed so there's nothing to verify.
4704 		 */
4705 		if (current_vd->vdev_top_zap == 0 ||
4706 		    zap_contains(spa_meta_objset(current),
4707 		    current_vd->vdev_top_zap,
4708 		    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
4709 			continue;
4710 
4711 		VERIFY0(zap_lookup(spa_meta_objset(current),
4712 		    current_vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
4713 		    sizeof (uint64_t), 1, &checkpoint_sm_obj));
4714 
4715 		VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(current),
4716 		    checkpoint_sm_obj, 0, current_vd->vdev_asize,
4717 		    current_vd->vdev_ashift));
4718 
4719 		verify_checkpoint_sm_entry_cb_arg_t vcsec;
4720 		vcsec.vcsec_vd = ckpoint_vd;
4721 		vcsec.vcsec_entryid = 0;
4722 		vcsec.vcsec_num_entries =
4723 		    space_map_length(checkpoint_sm) / sizeof (uint64_t);
4724 		VERIFY0(space_map_iterate(checkpoint_sm,
4725 		    space_map_length(checkpoint_sm),
4726 		    verify_checkpoint_sm_entry_cb, &vcsec));
4727 		dump_spacemap(current->spa_meta_objset, checkpoint_sm);
4728 		space_map_close(checkpoint_sm);
4729 	}
4730 
4731 	/*
4732 	 * If we've added vdevs since we took the checkpoint, ensure
4733 	 * that their checkpoint space maps are empty.
4734 	 */
4735 	if (ckpoint_rvd->vdev_children < current_rvd->vdev_children) {
4736 		for (uint64_t c = ckpoint_rvd->vdev_children;
4737 		    c < current_rvd->vdev_children; c++) {
4738 			vdev_t *current_vd = current_rvd->vdev_child[c];
4739 			ASSERT3P(current_vd->vdev_checkpoint_sm, ==, NULL);
4740 		}
4741 	}
4742 
4743 	/* for cleaner progress output */
4744 	(void) fprintf(stderr, "\n");
4745 }
4746 
4747 /*
4748  * Verifies that all space that's allocated in the checkpoint is
4749  * still allocated in the current version, by checking that everything
4750  * in checkpoint's ms_allocatable (which is actually allocated, not
4751  * allocatable/free) is not present in current's ms_allocatable.
4752  *
4753  * Note that the function changes the state of the ms_allocatable
4754  * trees of both spas when called. The entries of all ms_allocatable
4755  * trees are cleared out and then repopulated from their respective
4756  * ms_sm space maps. In the checkpointed state we load the allocated
4757  * entries, and in the current state we load the free entries.
4758  */
4759 static void
4760 verify_checkpoint_ms_spacemaps(spa_t *checkpoint, spa_t *current)
4761 {
4762 	vdev_t *ckpoint_rvd = checkpoint->spa_root_vdev;
4763 	vdev_t *current_rvd = current->spa_root_vdev;
4764 
4765 	load_concrete_ms_allocatable_trees(checkpoint, SM_ALLOC);
4766 	load_concrete_ms_allocatable_trees(current, SM_FREE);
4767 
4768 	for (uint64_t i = 0; i < ckpoint_rvd->vdev_children; i++) {
4769 		vdev_t *ckpoint_vd = ckpoint_rvd->vdev_child[i];
4770 		vdev_t *current_vd = current_rvd->vdev_child[i];
4771 
4772 		if (ckpoint_vd->vdev_ops == &vdev_indirect_ops) {
4773 			/*
4774 			 * See comment in verify_checkpoint_vdev_spacemaps()
4775 			 */
4776 			ASSERT3P(current_vd->vdev_ops, ==, &vdev_indirect_ops);
4777 			continue;
4778 		}
4779 
4780 		for (uint64_t m = 0; m < ckpoint_vd->vdev_ms_count; m++) {
4781 			metaslab_t *ckpoint_msp = ckpoint_vd->vdev_ms[m];
4782 			metaslab_t *current_msp = current_vd->vdev_ms[m];
4783 
4784 			(void) fprintf(stderr,
4785 			    "\rverifying vdev %llu of %llu, "
4786 			    "metaslab %llu of %llu ...",
4787 			    (longlong_t)current_vd->vdev_id,
4788 			    (longlong_t)current_rvd->vdev_children,
4789 			    (longlong_t)current_vd->vdev_ms[m]->ms_id,
4790 			    (longlong_t)current_vd->vdev_ms_count);
4791 
4792 			/*
4793 			 * We walk through the ms_allocatable trees that
4794 			 * are loaded with the allocated blocks from the
4795 			 * ms_sm spacemaps of the checkpoint. For each
4796 			 * one of these ranges we ensure that none of them
4797 			 * exists in the ms_allocatable trees of the
4798 			 * current state which are loaded with the ranges
4799 			 * that are currently free.
4800 			 *
4801 			 * This way we ensure that none of the blocks that
4802 			 * are part of the checkpoint were freed by mistake.
4803 			 */
4804 			range_tree_walk(ckpoint_msp->ms_allocatable,
4805 			    (range_tree_func_t *)range_tree_verify_not_present,
4806 			    current_msp->ms_allocatable);
4807 		}
4808 	}
4809 
4810 	/* for cleaner progress output */
4811 	(void) fprintf(stderr, "\n");
4812 }
4813 
4814 static void
4815 verify_checkpoint_blocks(spa_t *spa)
4816 {
4817 	ASSERT(!dump_opt['L']);
4818 
4819 	spa_t *checkpoint_spa;
4820 	char *checkpoint_pool;
4821 	nvlist_t *config = NULL;
4822 	int error = 0;
4823 
4824 	/*
4825 	 * We import the checkpointed state of the pool (under a different
4826 	 * name) so we can do verification on it against the current state
4827 	 * of the pool.
4828 	 */
4829 	checkpoint_pool = import_checkpointed_state(spa->spa_name, config,
4830 	    NULL);
4831 	ASSERT(strcmp(spa->spa_name, checkpoint_pool) != 0);
4832 
4833 	error = spa_open(checkpoint_pool, &checkpoint_spa, FTAG);
4834 	if (error != 0) {
4835 		fatal("Tried to open pool \"%s\" but spa_open() failed with "
4836 		    "error %d\n", checkpoint_pool, error);
4837 	}
4838 
4839 	/*
4840 	 * Ensure that ranges in the checkpoint space maps of each vdev
4841 	 * are allocated according to the checkpointed state's metaslab
4842 	 * space maps.
4843 	 */
4844 	verify_checkpoint_vdev_spacemaps(checkpoint_spa, spa);
4845 
4846 	/*
4847 	 * Ensure that allocated ranges in the checkpoint's metaslab
4848 	 * space maps remain allocated in the metaslab space maps of
4849 	 * the current state.
4850 	 */
4851 	verify_checkpoint_ms_spacemaps(checkpoint_spa, spa);
4852 
4853 	/*
4854 	 * Once we are done, we get rid of the checkpointed state.
4855 	 */
4856 	spa_close(checkpoint_spa, FTAG);
4857 	free(checkpoint_pool);
4858 }
4859 
4860 static void
4861 dump_leftover_checkpoint_blocks(spa_t *spa)
4862 {
4863 	vdev_t *rvd = spa->spa_root_vdev;
4864 
4865 	for (uint64_t i = 0; i < rvd->vdev_children; i++) {
4866 		vdev_t *vd = rvd->vdev_child[i];
4867 
4868 		space_map_t *checkpoint_sm = NULL;
4869 		uint64_t checkpoint_sm_obj;
4870 
4871 		if (vd->vdev_top_zap == 0)
4872 			continue;
4873 
4874 		if (zap_contains(spa_meta_objset(spa), vd->vdev_top_zap,
4875 		    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM) != 0)
4876 			continue;
4877 
4878 		VERIFY0(zap_lookup(spa_meta_objset(spa), vd->vdev_top_zap,
4879 		    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
4880 		    sizeof (uint64_t), 1, &checkpoint_sm_obj));
4881 
4882 		VERIFY0(space_map_open(&checkpoint_sm, spa_meta_objset(spa),
4883 		    checkpoint_sm_obj, 0, vd->vdev_asize, vd->vdev_ashift));
4884 		dump_spacemap(spa->spa_meta_objset, checkpoint_sm);
4885 		space_map_close(checkpoint_sm);
4886 	}
4887 }
4888 
4889 static int
4890 verify_checkpoint(spa_t *spa)
4891 {
4892 	uberblock_t checkpoint;
4893 	int error;
4894 
4895 	if (!spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT))
4896 		return (0);
4897 
4898 	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
4899 	    DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
4900 	    sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
4901 
4902 	if (error == ENOENT && !dump_opt['L']) {
4903 		/*
4904 		 * If the feature is active but the uberblock is missing
4905 		 * then we must be in the middle of discarding the
4906 		 * checkpoint.
4907 		 */
4908 		(void) printf("\nPartially discarded checkpoint "
4909 		    "state found:\n");
4910 		dump_leftover_checkpoint_blocks(spa);
4911 		return (0);
4912 	} else if (error != 0) {
4913 		(void) printf("lookup error %d when looking for "
4914 		    "checkpointed uberblock in MOS\n", error);
4915 		return (error);
4916 	}
4917 	dump_uberblock(&checkpoint, "\nCheckpointed uberblock found:\n", "\n");
4918 
4919 	if (checkpoint.ub_checkpoint_txg == 0) {
4920 		(void) printf("\nub_checkpoint_txg not set in checkpointed "
4921 		    "uberblock\n");
4922 		error = 3;
4923 	}
4924 
4925 	if (error == 0 && !dump_opt['L'])
4926 		verify_checkpoint_blocks(spa);
4927 
4928 	return (error);
4929 }
4930 
4931 /* ARGSUSED */
4932 static void
4933 mos_leaks_cb(void *arg, uint64_t start, uint64_t size)
4934 {
4935 	for (uint64_t i = start; i < size; i++) {
4936 		(void) printf("MOS object %llu referenced but not allocated\n",
4937 		    (u_longlong_t)i);
4938 	}
4939 }
4940 
4941 static range_tree_t *mos_refd_objs;
4942 
4943 static void
4944 mos_obj_refd(uint64_t obj)
4945 {
4946 	if (obj != 0 && mos_refd_objs != NULL)
4947 		range_tree_add(mos_refd_objs, obj, 1);
4948 }
4949 
4950 static void
4951 mos_leak_vdev_top_zap(vdev_t *vd)
4952 {
4953 	uint64_t ms_flush_data_obj;
4954 
4955 	int error = zap_lookup(spa_meta_objset(vd->vdev_spa),
4956 	    vd->vdev_top_zap, VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS,
4957 	    sizeof (ms_flush_data_obj), 1, &ms_flush_data_obj);
4958 	if (error == ENOENT)
4959 		return;
4960 	ASSERT0(error);
4961 
4962 	mos_obj_refd(ms_flush_data_obj);
4963 }
4964 
4965 static void
4966 mos_leak_vdev(vdev_t *vd)
4967 {
4968 	mos_obj_refd(vd->vdev_dtl_object);
4969 	mos_obj_refd(vd->vdev_ms_array);
4970 	mos_obj_refd(vd->vdev_indirect_config.vic_births_object);
4971 	mos_obj_refd(vd->vdev_indirect_config.vic_mapping_object);
4972 	mos_obj_refd(vd->vdev_leaf_zap);
4973 	if (vd->vdev_checkpoint_sm != NULL)
4974 		mos_obj_refd(vd->vdev_checkpoint_sm->sm_object);
4975 	if (vd->vdev_indirect_mapping != NULL) {
4976 		mos_obj_refd(vd->vdev_indirect_mapping->
4977 		    vim_phys->vimp_counts_object);
4978 	}
4979 	if (vd->vdev_obsolete_sm != NULL)
4980 		mos_obj_refd(vd->vdev_obsolete_sm->sm_object);
4981 
4982 	for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
4983 		metaslab_t *ms = vd->vdev_ms[m];
4984 		mos_obj_refd(space_map_object(ms->ms_sm));
4985 	}
4986 
4987 	if (vd->vdev_top_zap != 0) {
4988 		mos_obj_refd(vd->vdev_top_zap);
4989 		mos_leak_vdev_top_zap(vd);
4990 	}
4991 
4992 	for (uint64_t c = 0; c < vd->vdev_children; c++) {
4993 		mos_leak_vdev(vd->vdev_child[c]);
4994 	}
4995 }
4996 
4997 static void
4998 mos_leak_log_spacemaps(spa_t *spa)
4999 {
5000 	uint64_t spacemap_zap;
5001 
5002 	int error = zap_lookup(spa_meta_objset(spa),
5003 	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_LOG_SPACEMAP_ZAP,
5004 	    sizeof (spacemap_zap), 1, &spacemap_zap);
5005 	if (error == ENOENT)
5006 		return;
5007 	ASSERT0(error);
5008 
5009 	mos_obj_refd(spacemap_zap);
5010 	for (spa_log_sm_t *sls = avl_first(&spa->spa_sm_logs_by_txg);
5011 	    sls; sls = AVL_NEXT(&spa->spa_sm_logs_by_txg, sls))
5012 		mos_obj_refd(sls->sls_sm_obj);
5013 }
5014 
5015 static int
5016 dump_mos_leaks(spa_t *spa)
5017 {
5018 	int rv = 0;
5019 	objset_t *mos = spa->spa_meta_objset;
5020 	dsl_pool_t *dp = spa->spa_dsl_pool;
5021 
5022 	/* Visit and mark all referenced objects in the MOS */
5023 
5024 	mos_obj_refd(DMU_POOL_DIRECTORY_OBJECT);
5025 	mos_obj_refd(spa->spa_pool_props_object);
5026 	mos_obj_refd(spa->spa_config_object);
5027 	mos_obj_refd(spa->spa_ddt_stat_object);
5028 	mos_obj_refd(spa->spa_feat_desc_obj);
5029 	mos_obj_refd(spa->spa_feat_enabled_txg_obj);
5030 	mos_obj_refd(spa->spa_feat_for_read_obj);
5031 	mos_obj_refd(spa->spa_feat_for_write_obj);
5032 	mos_obj_refd(spa->spa_history);
5033 	mos_obj_refd(spa->spa_errlog_last);
5034 	mos_obj_refd(spa->spa_errlog_scrub);
5035 	mos_obj_refd(spa->spa_all_vdev_zaps);
5036 	mos_obj_refd(spa->spa_dsl_pool->dp_bptree_obj);
5037 	mos_obj_refd(spa->spa_dsl_pool->dp_tmp_userrefs_obj);
5038 	mos_obj_refd(spa->spa_dsl_pool->dp_scan->scn_phys.scn_queue_obj);
5039 	bpobj_count_refd(&spa->spa_deferred_bpobj);
5040 	mos_obj_refd(dp->dp_empty_bpobj);
5041 	bpobj_count_refd(&dp->dp_obsolete_bpobj);
5042 	bpobj_count_refd(&dp->dp_free_bpobj);
5043 	mos_obj_refd(spa->spa_l2cache.sav_object);
5044 	mos_obj_refd(spa->spa_spares.sav_object);
5045 
5046 	if (spa->spa_syncing_log_sm != NULL)
5047 		mos_obj_refd(spa->spa_syncing_log_sm->sm_object);
5048 	mos_leak_log_spacemaps(spa);
5049 
5050 	mos_obj_refd(spa->spa_condensing_indirect_phys.
5051 	    scip_next_mapping_object);
5052 	mos_obj_refd(spa->spa_condensing_indirect_phys.
5053 	    scip_prev_obsolete_sm_object);
5054 	if (spa->spa_condensing_indirect_phys.scip_next_mapping_object != 0) {
5055 		vdev_indirect_mapping_t *vim =
5056 		    vdev_indirect_mapping_open(mos,
5057 		    spa->spa_condensing_indirect_phys.scip_next_mapping_object);
5058 		mos_obj_refd(vim->vim_phys->vimp_counts_object);
5059 		vdev_indirect_mapping_close(vim);
5060 	}
5061 
5062 	if (dp->dp_origin_snap != NULL) {
5063 		dsl_dataset_t *ds;
5064 
5065 		dsl_pool_config_enter(dp, FTAG);
5066 		VERIFY0(dsl_dataset_hold_obj(dp,
5067 		    dsl_dataset_phys(dp->dp_origin_snap)->ds_next_snap_obj,
5068 		    FTAG, &ds));
5069 		count_ds_mos_objects(ds);
5070 		dump_deadlist(&ds->ds_deadlist);
5071 		dsl_dataset_rele(ds, FTAG);
5072 		dsl_pool_config_exit(dp, FTAG);
5073 
5074 		count_ds_mos_objects(dp->dp_origin_snap);
5075 		dump_deadlist(&dp->dp_origin_snap->ds_deadlist);
5076 	}
5077 	count_dir_mos_objects(dp->dp_mos_dir);
5078 	if (dp->dp_free_dir != NULL)
5079 		count_dir_mos_objects(dp->dp_free_dir);
5080 	if (dp->dp_leak_dir != NULL)
5081 		count_dir_mos_objects(dp->dp_leak_dir);
5082 
5083 	mos_leak_vdev(spa->spa_root_vdev);
5084 
5085 	for (uint64_t class = 0; class < DDT_CLASSES; class++) {
5086 		for (uint64_t type = 0; type < DDT_TYPES; type++) {
5087 			for (uint64_t cksum = 0;
5088 			    cksum < ZIO_CHECKSUM_FUNCTIONS; cksum++) {
5089 				ddt_t *ddt = spa->spa_ddt[cksum];
5090 				mos_obj_refd(ddt->ddt_object[type][class]);
5091 			}
5092 		}
5093 	}
5094 
5095 	/*
5096 	 * Visit all allocated objects and make sure they are referenced.
5097 	 */
5098 	uint64_t object = 0;
5099 	while (dmu_object_next(mos, &object, B_FALSE, 0) == 0) {
5100 		if (range_tree_contains(mos_refd_objs, object, 1)) {
5101 			range_tree_remove(mos_refd_objs, object, 1);
5102 		} else {
5103 			dmu_object_info_t doi;
5104 			const char *name;
5105 			dmu_object_info(mos, object, &doi);
5106 			if (doi.doi_type & DMU_OT_NEWTYPE) {
5107 				dmu_object_byteswap_t bswap =
5108 				    DMU_OT_BYTESWAP(doi.doi_type);
5109 				name = dmu_ot_byteswap[bswap].ob_name;
5110 			} else {
5111 				name = dmu_ot[doi.doi_type].ot_name;
5112 			}
5113 
5114 			(void) printf("MOS object %llu (%s) leaked\n",
5115 			    (u_longlong_t)object, name);
5116 			rv = 2;
5117 		}
5118 	}
5119 	(void) range_tree_walk(mos_refd_objs, mos_leaks_cb, NULL);
5120 	if (!range_tree_is_empty(mos_refd_objs))
5121 		rv = 2;
5122 	range_tree_vacate(mos_refd_objs, NULL, NULL);
5123 	range_tree_destroy(mos_refd_objs);
5124 	return (rv);
5125 }
5126 
5127 typedef struct log_sm_obsolete_stats_arg {
5128 	uint64_t lsos_current_txg;
5129 
5130 	uint64_t lsos_total_entries;
5131 	uint64_t lsos_valid_entries;
5132 
5133 	uint64_t lsos_sm_entries;
5134 	uint64_t lsos_valid_sm_entries;
5135 } log_sm_obsolete_stats_arg_t;
5136 
5137 static int
5138 log_spacemap_obsolete_stats_cb(spa_t *spa, space_map_entry_t *sme,
5139     uint64_t txg, void *arg)
5140 {
5141 	log_sm_obsolete_stats_arg_t *lsos = arg;
5142 	uint64_t offset = sme->sme_offset;
5143 	uint64_t vdev_id = sme->sme_vdev;
5144 
5145 	if (lsos->lsos_current_txg == 0) {
5146 		/* this is the first log */
5147 		lsos->lsos_current_txg = txg;
5148 	} else if (lsos->lsos_current_txg < txg) {
5149 		/* we just changed log - print stats and reset */
5150 		(void) printf("%-8llu valid entries out of %-8llu - txg %llu\n",
5151 		    (u_longlong_t)lsos->lsos_valid_sm_entries,
5152 		    (u_longlong_t)lsos->lsos_sm_entries,
5153 		    (u_longlong_t)lsos->lsos_current_txg);
5154 		lsos->lsos_valid_sm_entries = 0;
5155 		lsos->lsos_sm_entries = 0;
5156 		lsos->lsos_current_txg = txg;
5157 	}
5158 	ASSERT3U(lsos->lsos_current_txg, ==, txg);
5159 
5160 	lsos->lsos_sm_entries++;
5161 	lsos->lsos_total_entries++;
5162 
5163 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
5164 	if (!vdev_is_concrete(vd))
5165 		return (0);
5166 
5167 	metaslab_t *ms = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5168 	ASSERT(sme->sme_type == SM_ALLOC || sme->sme_type == SM_FREE);
5169 
5170 	if (txg < metaslab_unflushed_txg(ms))
5171 		return (0);
5172 	lsos->lsos_valid_sm_entries++;
5173 	lsos->lsos_valid_entries++;
5174 	return (0);
5175 }
5176 
5177 static void
5178 dump_log_spacemap_obsolete_stats(spa_t *spa)
5179 {
5180 	if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP))
5181 		return;
5182 
5183 	log_sm_obsolete_stats_arg_t lsos;
5184 	bzero(&lsos, sizeof (lsos));
5185 
5186 	(void) printf("Log Space Map Obsolete Entry Statistics:\n");
5187 
5188 	iterate_through_spacemap_logs(spa,
5189 	    log_spacemap_obsolete_stats_cb, &lsos);
5190 
5191 	/* print stats for latest log */
5192 	(void) printf("%-8llu valid entries out of %-8llu - txg %llu\n",
5193 	    (u_longlong_t)lsos.lsos_valid_sm_entries,
5194 	    (u_longlong_t)lsos.lsos_sm_entries,
5195 	    (u_longlong_t)lsos.lsos_current_txg);
5196 
5197 	(void) printf("%-8llu valid entries out of %-8llu - total\n\n",
5198 	    (u_longlong_t)lsos.lsos_valid_entries,
5199 	    (u_longlong_t)lsos.lsos_total_entries);
5200 }
5201 
5202 static void
5203 dump_zpool(spa_t *spa)
5204 {
5205 	dsl_pool_t *dp = spa_get_dsl(spa);
5206 	int rc = 0;
5207 
5208 	if (dump_opt['S']) {
5209 		dump_simulated_ddt(spa);
5210 		return;
5211 	}
5212 
5213 	if (!dump_opt['e'] && dump_opt['C'] > 1) {
5214 		(void) printf("\nCached configuration:\n");
5215 		dump_nvlist(spa->spa_config, 8);
5216 	}
5217 
5218 	if (dump_opt['C'])
5219 		dump_config(spa);
5220 
5221 	if (dump_opt['u'])
5222 		dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
5223 
5224 	if (dump_opt['D'])
5225 		dump_all_ddts(spa);
5226 
5227 	if (dump_opt['d'] > 2 || dump_opt['m'])
5228 		dump_metaslabs(spa);
5229 	if (dump_opt['M'])
5230 		dump_metaslab_groups(spa);
5231 	if (dump_opt['d'] > 2 || dump_opt['m']) {
5232 		dump_log_spacemaps(spa);
5233 		dump_log_spacemap_obsolete_stats(spa);
5234 	}
5235 
5236 	if (dump_opt['d'] || dump_opt['i']) {
5237 		mos_refd_objs = range_tree_create(NULL, RANGE_SEG64, NULL, 0,
5238 		    0);
5239 		dump_dir(dp->dp_meta_objset);
5240 
5241 		if (dump_opt['d'] >= 3) {
5242 			dsl_pool_t *dp = spa->spa_dsl_pool;
5243 			dump_full_bpobj(&spa->spa_deferred_bpobj,
5244 			    "Deferred frees", 0);
5245 			if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
5246 				dump_full_bpobj(&dp->dp_free_bpobj,
5247 				    "Pool snapshot frees", 0);
5248 			}
5249 			if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
5250 				ASSERT(spa_feature_is_enabled(spa,
5251 				    SPA_FEATURE_DEVICE_REMOVAL));
5252 				dump_full_bpobj(&dp->dp_obsolete_bpobj,
5253 				    "Pool obsolete blocks", 0);
5254 			}
5255 
5256 			if (spa_feature_is_active(spa,
5257 			    SPA_FEATURE_ASYNC_DESTROY)) {
5258 				dump_bptree(spa->spa_meta_objset,
5259 				    dp->dp_bptree_obj,
5260 				    "Pool dataset frees");
5261 			}
5262 			dump_dtl(spa->spa_root_vdev, 0);
5263 		}
5264 		(void) dmu_objset_find(spa_name(spa), dump_one_dir,
5265 		    NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
5266 
5267 		if (rc == 0 && !dump_opt['L'])
5268 			rc = dump_mos_leaks(spa);
5269 
5270 		for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
5271 			uint64_t refcount;
5272 
5273 			if (!(spa_feature_table[f].fi_flags &
5274 			    ZFEATURE_FLAG_PER_DATASET) ||
5275 			    !spa_feature_is_enabled(spa, f)) {
5276 				ASSERT0(dataset_feature_count[f]);
5277 				continue;
5278 			}
5279 			(void) feature_get_refcount(spa,
5280 			    &spa_feature_table[f], &refcount);
5281 			if (dataset_feature_count[f] != refcount) {
5282 				(void) printf("%s feature refcount mismatch: "
5283 				    "%lld datasets != %lld refcount\n",
5284 				    spa_feature_table[f].fi_uname,
5285 				    (longlong_t)dataset_feature_count[f],
5286 				    (longlong_t)refcount);
5287 				rc = 2;
5288 			} else {
5289 				(void) printf("Verified %s feature refcount "
5290 				    "of %llu is correct\n",
5291 				    spa_feature_table[f].fi_uname,
5292 				    (longlong_t)refcount);
5293 			}
5294 		}
5295 
5296 		if (rc == 0)
5297 			rc = verify_device_removal_feature_counts(spa);
5298 	}
5299 
5300 	if (rc == 0 && (dump_opt['b'] || dump_opt['c']))
5301 		rc = dump_block_stats(spa);
5302 
5303 	if (rc == 0)
5304 		rc = verify_spacemap_refcounts(spa);
5305 
5306 	if (dump_opt['s'])
5307 		show_pool_stats(spa);
5308 
5309 	if (dump_opt['h'])
5310 		dump_history(spa);
5311 
5312 	if (rc == 0)
5313 		rc = verify_checkpoint(spa);
5314 
5315 	if (rc != 0) {
5316 		dump_debug_buffer();
5317 		exit(rc);
5318 	}
5319 }
5320 
5321 #define	ZDB_FLAG_CHECKSUM	0x0001
5322 #define	ZDB_FLAG_DECOMPRESS	0x0002
5323 #define	ZDB_FLAG_BSWAP		0x0004
5324 #define	ZDB_FLAG_GBH		0x0008
5325 #define	ZDB_FLAG_INDIRECT	0x0010
5326 #define	ZDB_FLAG_PHYS		0x0020
5327 #define	ZDB_FLAG_RAW		0x0040
5328 #define	ZDB_FLAG_PRINT_BLKPTR	0x0080
5329 
5330 static int flagbits[256];
5331 
5332 static void
5333 zdb_print_blkptr(blkptr_t *bp, int flags)
5334 {
5335 	char blkbuf[BP_SPRINTF_LEN];
5336 
5337 	if (flags & ZDB_FLAG_BSWAP)
5338 		byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
5339 
5340 	snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
5341 	(void) printf("%s\n", blkbuf);
5342 }
5343 
5344 static void
5345 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
5346 {
5347 	int i;
5348 
5349 	for (i = 0; i < nbps; i++)
5350 		zdb_print_blkptr(&bp[i], flags);
5351 }
5352 
5353 static void
5354 zdb_dump_gbh(void *buf, int flags)
5355 {
5356 	zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
5357 }
5358 
5359 static void
5360 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
5361 {
5362 	if (flags & ZDB_FLAG_BSWAP)
5363 		byteswap_uint64_array(buf, size);
5364 	(void) write(1, buf, size);
5365 }
5366 
5367 static void
5368 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
5369 {
5370 	uint64_t *d = (uint64_t *)buf;
5371 	unsigned nwords = size / sizeof (uint64_t);
5372 	int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
5373 	unsigned i, j;
5374 	const char *hdr;
5375 	char *c;
5376 
5377 
5378 	if (do_bswap)
5379 		hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
5380 	else
5381 		hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
5382 
5383 	(void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
5384 
5385 	for (i = 0; i < nwords; i += 2) {
5386 		(void) printf("%06llx:  %016llx  %016llx  ",
5387 		    (u_longlong_t)(i * sizeof (uint64_t)),
5388 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
5389 		    (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
5390 
5391 		c = (char *)&d[i];
5392 		for (j = 0; j < 2 * sizeof (uint64_t); j++)
5393 			(void) printf("%c", isprint(c[j]) ? c[j] : '.');
5394 		(void) printf("\n");
5395 	}
5396 }
5397 
5398 /*
5399  * There are two acceptable formats:
5400  *	leaf_name	  - For example: c1t0d0 or /tmp/ztest.0a
5401  *	child[.child]*    - For example: 0.1.1
5402  *
5403  * The second form can be used to specify arbitrary vdevs anywhere
5404  * in the heirarchy.  For example, in a pool with a mirror of
5405  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
5406  */
5407 static vdev_t *
5408 zdb_vdev_lookup(vdev_t *vdev, const char *path)
5409 {
5410 	char *s, *p, *q;
5411 	unsigned i;
5412 
5413 	if (vdev == NULL)
5414 		return (NULL);
5415 
5416 	/* First, assume the x.x.x.x format */
5417 	i = strtoul(path, &s, 10);
5418 	if (s == path || (s && *s != '.' && *s != '\0'))
5419 		goto name;
5420 	if (i >= vdev->vdev_children)
5421 		return (NULL);
5422 
5423 	vdev = vdev->vdev_child[i];
5424 	if (*s == '\0')
5425 		return (vdev);
5426 	return (zdb_vdev_lookup(vdev, s+1));
5427 
5428 name:
5429 	for (i = 0; i < vdev->vdev_children; i++) {
5430 		vdev_t *vc = vdev->vdev_child[i];
5431 
5432 		if (vc->vdev_path == NULL) {
5433 			vc = zdb_vdev_lookup(vc, path);
5434 			if (vc == NULL)
5435 				continue;
5436 			else
5437 				return (vc);
5438 		}
5439 
5440 		p = strrchr(vc->vdev_path, '/');
5441 		p = p ? p + 1 : vc->vdev_path;
5442 		q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
5443 
5444 		if (strcmp(vc->vdev_path, path) == 0)
5445 			return (vc);
5446 		if (strcmp(p, path) == 0)
5447 			return (vc);
5448 		if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
5449 			return (vc);
5450 	}
5451 
5452 	return (NULL);
5453 }
5454 
5455 /* ARGSUSED */
5456 static int
5457 random_get_pseudo_bytes_cb(void *buf, size_t len, void *unused)
5458 {
5459 	return (random_get_pseudo_bytes(buf, len));
5460 }
5461 
5462 /*
5463  * Read a block from a pool and print it out.  The syntax of the
5464  * block descriptor is:
5465  *
5466  *	pool:vdev_specifier:offset:size[:flags]
5467  *
5468  *	pool           - The name of the pool you wish to read from
5469  *	vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
5470  *	offset         - offset, in hex, in bytes
5471  *	size           - Amount of data to read, in hex, in bytes
5472  *	flags          - A string of characters specifying options
5473  *		 b: Decode a blkptr at given offset within block
5474  *		*c: Calculate and display checksums
5475  *		 d: Decompress data before dumping
5476  *		 e: Byteswap data before dumping
5477  *		 g: Display data as a gang block header
5478  *		 i: Display as an indirect block
5479  *		 p: Do I/O to physical offset
5480  *		 r: Dump raw data to stdout
5481  *
5482  *              * = not yet implemented
5483  */
5484 static void
5485 zdb_read_block(char *thing, spa_t *spa)
5486 {
5487 	blkptr_t blk, *bp = &blk;
5488 	dva_t *dva = bp->blk_dva;
5489 	int flags = 0;
5490 	uint64_t offset = 0, size = 0, psize = 0, lsize = 0, blkptr_offset = 0;
5491 	zio_t *zio;
5492 	vdev_t *vd;
5493 	abd_t *pabd;
5494 	void *lbuf, *buf;
5495 	const char *s, *vdev;
5496 	char *p, *dup, *flagstr;
5497 	int i, error;
5498 
5499 	dup = strdup(thing);
5500 	s = strtok(dup, ":");
5501 	vdev = s ? s : "";
5502 	s = strtok(NULL, ":");
5503 	offset = strtoull(s ? s : "", NULL, 16);
5504 	s = strtok(NULL, ":");
5505 	size = strtoull(s ? s : "", NULL, 16);
5506 	s = strtok(NULL, ":");
5507 	if (s)
5508 		flagstr = strdup(s);
5509 	else
5510 		flagstr = strdup("");
5511 
5512 	s = NULL;
5513 	if (size == 0)
5514 		s = "size must not be zero";
5515 	if (!IS_P2ALIGNED(size, DEV_BSIZE))
5516 		s = "size must be a multiple of sector size";
5517 	if (!IS_P2ALIGNED(offset, DEV_BSIZE))
5518 		s = "offset must be a multiple of sector size";
5519 	if (s) {
5520 		(void) printf("Invalid block specifier: %s  - %s\n", thing, s);
5521 		free(dup);
5522 		return;
5523 	}
5524 
5525 	for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
5526 		for (i = 0; flagstr[i]; i++) {
5527 			int bit = flagbits[(uchar_t)flagstr[i]];
5528 
5529 			if (bit == 0) {
5530 				(void) printf("***Invalid flag: %c\n",
5531 				    flagstr[i]);
5532 				continue;
5533 			}
5534 			flags |= bit;
5535 
5536 			/* If it's not something with an argument, keep going */
5537 			if ((bit & (ZDB_FLAG_CHECKSUM |
5538 			    ZDB_FLAG_PRINT_BLKPTR)) == 0)
5539 				continue;
5540 
5541 			p = &flagstr[i + 1];
5542 			if (bit == ZDB_FLAG_PRINT_BLKPTR)
5543 				blkptr_offset = strtoull(p, &p, 16);
5544 			if (*p != ':' && *p != '\0') {
5545 				(void) printf("***Invalid flag arg: '%s'\n", s);
5546 				free(dup);
5547 				return;
5548 			}
5549 		}
5550 	}
5551 	free(flagstr);
5552 
5553 	vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
5554 	if (vd == NULL) {
5555 		(void) printf("***Invalid vdev: %s\n", vdev);
5556 		free(dup);
5557 		return;
5558 	} else {
5559 		if (vd->vdev_path)
5560 			(void) fprintf(stderr, "Found vdev: %s\n",
5561 			    vd->vdev_path);
5562 		else
5563 			(void) fprintf(stderr, "Found vdev type: %s\n",
5564 			    vd->vdev_ops->vdev_op_type);
5565 	}
5566 
5567 	psize = size;
5568 	lsize = size;
5569 
5570 	pabd = abd_alloc_linear(SPA_MAXBLOCKSIZE, B_FALSE);
5571 	lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
5572 
5573 	BP_ZERO(bp);
5574 
5575 	DVA_SET_VDEV(&dva[0], vd->vdev_id);
5576 	DVA_SET_OFFSET(&dva[0], offset);
5577 	DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
5578 	DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
5579 
5580 	BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
5581 
5582 	BP_SET_LSIZE(bp, lsize);
5583 	BP_SET_PSIZE(bp, psize);
5584 	BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
5585 	BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
5586 	BP_SET_TYPE(bp, DMU_OT_NONE);
5587 	BP_SET_LEVEL(bp, 0);
5588 	BP_SET_DEDUP(bp, 0);
5589 	BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
5590 
5591 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
5592 	zio = zio_root(spa, NULL, NULL, 0);
5593 
5594 	if (vd == vd->vdev_top) {
5595 		/*
5596 		 * Treat this as a normal block read.
5597 		 */
5598 		zio_nowait(zio_read(zio, spa, bp, pabd, psize, NULL, NULL,
5599 		    ZIO_PRIORITY_SYNC_READ,
5600 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
5601 	} else {
5602 		/*
5603 		 * Treat this as a vdev child I/O.
5604 		 */
5605 		zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pabd,
5606 		    psize, ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
5607 		    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
5608 		    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
5609 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW | ZIO_FLAG_OPTIONAL,
5610 		    NULL, NULL));
5611 	}
5612 
5613 	error = zio_wait(zio);
5614 	spa_config_exit(spa, SCL_STATE, FTAG);
5615 
5616 	if (error) {
5617 		(void) printf("Read of %s failed, error: %d\n", thing, error);
5618 		goto out;
5619 	}
5620 
5621 	if (flags & ZDB_FLAG_DECOMPRESS) {
5622 		/*
5623 		 * We don't know how the data was compressed, so just try
5624 		 * every decompress function at every inflated blocksize.
5625 		 */
5626 		enum zio_compress c;
5627 		void *pbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
5628 		void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
5629 
5630 		abd_copy_to_buf(pbuf2, pabd, psize);
5631 
5632 		VERIFY0(abd_iterate_func(pabd, psize, SPA_MAXBLOCKSIZE - psize,
5633 		    random_get_pseudo_bytes_cb, NULL));
5634 
5635 		VERIFY0(random_get_pseudo_bytes((uint8_t *)pbuf2 + psize,
5636 		    SPA_MAXBLOCKSIZE - psize));
5637 
5638 		for (lsize = SPA_MAXBLOCKSIZE; lsize > psize;
5639 		    lsize -= SPA_MINBLOCKSIZE) {
5640 			for (c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++) {
5641 				if (zio_decompress_data(c, pabd,
5642 				    lbuf, psize, lsize) == 0 &&
5643 				    zio_decompress_data_buf(c, pbuf2,
5644 				    lbuf2, psize, lsize) == 0 &&
5645 				    bcmp(lbuf, lbuf2, lsize) == 0)
5646 					break;
5647 			}
5648 			if (c != ZIO_COMPRESS_FUNCTIONS)
5649 				break;
5650 			lsize -= SPA_MINBLOCKSIZE;
5651 		}
5652 
5653 		umem_free(pbuf2, SPA_MAXBLOCKSIZE);
5654 		umem_free(lbuf2, SPA_MAXBLOCKSIZE);
5655 
5656 		if (lsize <= psize) {
5657 			(void) printf("Decompress of %s failed\n", thing);
5658 			goto out;
5659 		}
5660 		buf = lbuf;
5661 		size = lsize;
5662 	} else {
5663 		buf = abd_to_buf(pabd);
5664 		size = psize;
5665 	}
5666 
5667 	if (flags & ZDB_FLAG_PRINT_BLKPTR)
5668 		zdb_print_blkptr((blkptr_t *)(void *)
5669 		    ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
5670 	else if (flags & ZDB_FLAG_RAW)
5671 		zdb_dump_block_raw(buf, size, flags);
5672 	else if (flags & ZDB_FLAG_INDIRECT)
5673 		zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
5674 		    flags);
5675 	else if (flags & ZDB_FLAG_GBH)
5676 		zdb_dump_gbh(buf, flags);
5677 	else
5678 		zdb_dump_block(thing, buf, size, flags);
5679 
5680 out:
5681 	abd_free(pabd);
5682 	umem_free(lbuf, SPA_MAXBLOCKSIZE);
5683 	free(dup);
5684 }
5685 
5686 static void
5687 zdb_embedded_block(char *thing)
5688 {
5689 	blkptr_t bp;
5690 	unsigned long long *words = (void *)&bp;
5691 	char *buf;
5692 	int err;
5693 
5694 	bzero(&bp, sizeof (bp));
5695 	err = sscanf(thing, "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx:"
5696 	    "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx",
5697 	    words + 0, words + 1, words + 2, words + 3,
5698 	    words + 4, words + 5, words + 6, words + 7,
5699 	    words + 8, words + 9, words + 10, words + 11,
5700 	    words + 12, words + 13, words + 14, words + 15);
5701 	if (err != 16) {
5702 		(void) fprintf(stderr, "invalid input format\n");
5703 		exit(1);
5704 	}
5705 	ASSERT3U(BPE_GET_LSIZE(&bp), <=, SPA_MAXBLOCKSIZE);
5706 	buf = malloc(SPA_MAXBLOCKSIZE);
5707 	if (buf == NULL) {
5708 		(void) fprintf(stderr, "out of memory\n");
5709 		exit(1);
5710 	}
5711 	err = decode_embedded_bp(&bp, buf, BPE_GET_LSIZE(&bp));
5712 	if (err != 0) {
5713 		(void) fprintf(stderr, "decode failed: %u\n", err);
5714 		exit(1);
5715 	}
5716 	zdb_dump_block_raw(buf, BPE_GET_LSIZE(&bp), 0);
5717 	free(buf);
5718 }
5719 
5720 int
5721 main(int argc, char **argv)
5722 {
5723 	int c;
5724 	struct rlimit rl = { 1024, 1024 };
5725 	spa_t *spa = NULL;
5726 	objset_t *os = NULL;
5727 	int dump_all = 1;
5728 	int verbose = 0;
5729 	int error = 0;
5730 	char **searchdirs = NULL;
5731 	int nsearch = 0;
5732 	char *target, *target_pool;
5733 	nvlist_t *policy = NULL;
5734 	uint64_t max_txg = UINT64_MAX;
5735 	int flags = ZFS_IMPORT_MISSING_LOG;
5736 	int rewind = ZPOOL_NEVER_REWIND;
5737 	char *spa_config_path_env;
5738 	boolean_t target_is_spa = B_TRUE;
5739 	nvlist_t *cfg = NULL;
5740 
5741 	(void) setrlimit(RLIMIT_NOFILE, &rl);
5742 	(void) enable_extended_FILE_stdio(-1, -1);
5743 
5744 	dprintf_setup(&argc, argv);
5745 
5746 	/*
5747 	 * If there is an environment variable SPA_CONFIG_PATH it overrides
5748 	 * default spa_config_path setting. If -U flag is specified it will
5749 	 * override this environment variable settings once again.
5750 	 */
5751 	spa_config_path_env = getenv("SPA_CONFIG_PATH");
5752 	if (spa_config_path_env != NULL)
5753 		spa_config_path = spa_config_path_env;
5754 
5755 	/*
5756 	 * For performance reasons, we set this tunable down. We do so before
5757 	 * the arg parsing section so that the user can override this value if
5758 	 * they choose.
5759 	 */
5760 	zfs_btree_verify_intensity = 3;
5761 
5762 	while ((c = getopt(argc, argv,
5763 	    "AbcCdDeEFGhiI:klLmMo:Op:PqRsSt:uU:vVx:X")) != -1) {
5764 		switch (c) {
5765 		case 'b':
5766 		case 'c':
5767 		case 'C':
5768 		case 'd':
5769 		case 'D':
5770 		case 'E':
5771 		case 'G':
5772 		case 'h':
5773 		case 'i':
5774 		case 'l':
5775 		case 'm':
5776 		case 'M':
5777 		case 'O':
5778 		case 'R':
5779 		case 's':
5780 		case 'S':
5781 		case 'u':
5782 			dump_opt[c]++;
5783 			dump_all = 0;
5784 			break;
5785 		case 'A':
5786 		case 'e':
5787 		case 'F':
5788 		case 'k':
5789 		case 'L':
5790 		case 'P':
5791 		case 'q':
5792 		case 'X':
5793 			dump_opt[c]++;
5794 			break;
5795 		/* NB: Sort single match options below. */
5796 		case 'I':
5797 			max_inflight = strtoull(optarg, NULL, 0);
5798 			if (max_inflight == 0) {
5799 				(void) fprintf(stderr, "maximum number "
5800 				    "of inflight I/Os must be greater "
5801 				    "than 0\n");
5802 				usage();
5803 			}
5804 			break;
5805 		case 'o':
5806 			error = set_global_var(optarg);
5807 			if (error != 0)
5808 				usage();
5809 			break;
5810 		case 'p':
5811 			if (searchdirs == NULL) {
5812 				searchdirs = umem_alloc(sizeof (char *),
5813 				    UMEM_NOFAIL);
5814 			} else {
5815 				char **tmp = umem_alloc((nsearch + 1) *
5816 				    sizeof (char *), UMEM_NOFAIL);
5817 				bcopy(searchdirs, tmp, nsearch *
5818 				    sizeof (char *));
5819 				umem_free(searchdirs,
5820 				    nsearch * sizeof (char *));
5821 				searchdirs = tmp;
5822 			}
5823 			searchdirs[nsearch++] = optarg;
5824 			break;
5825 		case 't':
5826 			max_txg = strtoull(optarg, NULL, 0);
5827 			if (max_txg < TXG_INITIAL) {
5828 				(void) fprintf(stderr, "incorrect txg "
5829 				    "specified: %s\n", optarg);
5830 				usage();
5831 			}
5832 			break;
5833 		case 'U':
5834 			spa_config_path = optarg;
5835 			if (spa_config_path[0] != '/') {
5836 				(void) fprintf(stderr,
5837 				    "cachefile must be an absolute path "
5838 				    "(i.e. start with a slash)\n");
5839 				usage();
5840 			}
5841 			break;
5842 		case 'v':
5843 			verbose++;
5844 			break;
5845 		case 'V':
5846 			flags = ZFS_IMPORT_VERBATIM;
5847 			break;
5848 		case 'x':
5849 			vn_dumpdir = optarg;
5850 			break;
5851 		default:
5852 			usage();
5853 			break;
5854 		}
5855 	}
5856 
5857 	if (!dump_opt['e'] && searchdirs != NULL) {
5858 		(void) fprintf(stderr, "-p option requires use of -e\n");
5859 		usage();
5860 	}
5861 
5862 	/*
5863 	 * ZDB does not typically re-read blocks; therefore limit the ARC
5864 	 * to 256 MB, which can be used entirely for metadata.
5865 	 */
5866 	zfs_arc_max = zfs_arc_meta_limit = 256 * 1024 * 1024;
5867 
5868 	/*
5869 	 * "zdb -c" uses checksum-verifying scrub i/os which are async reads.
5870 	 * "zdb -b" uses traversal prefetch which uses async reads.
5871 	 * For good performance, let several of them be active at once.
5872 	 */
5873 	zfs_vdev_async_read_max_active = 10;
5874 
5875 	/*
5876 	 * Disable reference tracking for better performance.
5877 	 */
5878 	reference_tracking_enable = B_FALSE;
5879 
5880 	/*
5881 	 * Do not fail spa_load when spa_load_verify fails. This is needed
5882 	 * to load non-idle pools.
5883 	 */
5884 	spa_load_verify_dryrun = B_TRUE;
5885 
5886 	kernel_init(FREAD);
5887 	g_zfs = libzfs_init();
5888 	ASSERT(g_zfs != NULL);
5889 
5890 	if (dump_all)
5891 		verbose = MAX(verbose, 1);
5892 
5893 	for (c = 0; c < 256; c++) {
5894 		if (dump_all && strchr("AeEFklLOPRSX", c) == NULL)
5895 			dump_opt[c] = 1;
5896 		if (dump_opt[c])
5897 			dump_opt[c] += verbose;
5898 	}
5899 
5900 	aok = (dump_opt['A'] == 1) || (dump_opt['A'] > 2);
5901 	zfs_recover = (dump_opt['A'] > 1);
5902 
5903 	argc -= optind;
5904 	argv += optind;
5905 
5906 	if (argc < 2 && dump_opt['R'])
5907 		usage();
5908 
5909 	if (dump_opt['E']) {
5910 		if (argc != 1)
5911 			usage();
5912 		zdb_embedded_block(argv[0]);
5913 		return (0);
5914 	}
5915 
5916 	if (argc < 1) {
5917 		if (!dump_opt['e'] && dump_opt['C']) {
5918 			dump_cachefile(spa_config_path);
5919 			return (0);
5920 		}
5921 		usage();
5922 	}
5923 
5924 	if (dump_opt['l'])
5925 		return (dump_label(argv[0]));
5926 
5927 	if (dump_opt['O']) {
5928 		if (argc != 2)
5929 			usage();
5930 		dump_opt['v'] = verbose + 3;
5931 		return (dump_path(argv[0], argv[1]));
5932 	}
5933 
5934 	if (dump_opt['X'] || dump_opt['F'])
5935 		rewind = ZPOOL_DO_REWIND |
5936 		    (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
5937 
5938 	if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
5939 	    nvlist_add_uint64(policy, ZPOOL_LOAD_REQUEST_TXG, max_txg) != 0 ||
5940 	    nvlist_add_uint32(policy, ZPOOL_LOAD_REWIND_POLICY, rewind) != 0)
5941 		fatal("internal error: %s", strerror(ENOMEM));
5942 
5943 	error = 0;
5944 	target = argv[0];
5945 
5946 	if (strpbrk(target, "/@") != NULL) {
5947 		size_t targetlen;
5948 
5949 		target_pool = strdup(target);
5950 		*strpbrk(target_pool, "/@") = '\0';
5951 
5952 		target_is_spa = B_FALSE;
5953 		targetlen = strlen(target);
5954 		if (targetlen && target[targetlen - 1] == '/')
5955 			target[targetlen - 1] = '\0';
5956 	} else {
5957 		target_pool = target;
5958 	}
5959 
5960 	if (dump_opt['e']) {
5961 		importargs_t args = { 0 };
5962 
5963 		args.paths = nsearch;
5964 		args.path = searchdirs;
5965 		args.can_be_active = B_TRUE;
5966 
5967 		error = zpool_tryimport(g_zfs, target_pool, &cfg, &args);
5968 
5969 		if (error == 0) {
5970 
5971 			if (nvlist_add_nvlist(cfg,
5972 			    ZPOOL_LOAD_POLICY, policy) != 0) {
5973 				fatal("can't open '%s': %s",
5974 				    target, strerror(ENOMEM));
5975 			}
5976 
5977 			if (dump_opt['C'] > 1) {
5978 				(void) printf("\nConfiguration for import:\n");
5979 				dump_nvlist(cfg, 8);
5980 			}
5981 
5982 			/*
5983 			 * Disable the activity check to allow examination of
5984 			 * active pools.
5985 			 */
5986 			error = spa_import(target_pool, cfg, NULL,
5987 			    flags | ZFS_IMPORT_SKIP_MMP);
5988 		}
5989 	}
5990 
5991 	char *checkpoint_pool = NULL;
5992 	char *checkpoint_target = NULL;
5993 	if (dump_opt['k']) {
5994 		checkpoint_pool = import_checkpointed_state(target, cfg,
5995 		    &checkpoint_target);
5996 
5997 		if (checkpoint_target != NULL)
5998 			target = checkpoint_target;
5999 
6000 	}
6001 
6002 	if (error == 0) {
6003 		if (dump_opt['k'] && (target_is_spa || dump_opt['R'])) {
6004 			ASSERT(checkpoint_pool != NULL);
6005 			ASSERT(checkpoint_target == NULL);
6006 
6007 			error = spa_open(checkpoint_pool, &spa, FTAG);
6008 			if (error != 0) {
6009 				fatal("Tried to open pool \"%s\" but "
6010 				    "spa_open() failed with error %d\n",
6011 				    checkpoint_pool, error);
6012 			}
6013 
6014 		} else if (target_is_spa || dump_opt['R']) {
6015 			zdb_set_skip_mmp(target);
6016 			error = spa_open_rewind(target, &spa, FTAG, policy,
6017 			    NULL);
6018 			if (error) {
6019 				/*
6020 				 * If we're missing the log device then
6021 				 * try opening the pool after clearing the
6022 				 * log state.
6023 				 */
6024 				mutex_enter(&spa_namespace_lock);
6025 				if ((spa = spa_lookup(target)) != NULL &&
6026 				    spa->spa_log_state == SPA_LOG_MISSING) {
6027 					spa->spa_log_state = SPA_LOG_CLEAR;
6028 					error = 0;
6029 				}
6030 				mutex_exit(&spa_namespace_lock);
6031 
6032 				if (!error) {
6033 					error = spa_open_rewind(target, &spa,
6034 					    FTAG, policy, NULL);
6035 				}
6036 			}
6037 		} else {
6038 			zdb_set_skip_mmp(target);
6039 			error = open_objset(target, DMU_OST_ANY, FTAG, &os);
6040 		}
6041 	}
6042 	nvlist_free(policy);
6043 
6044 	if (error)
6045 		fatal("can't open '%s': %s", target, strerror(error));
6046 
6047 	argv++;
6048 	argc--;
6049 	if (!dump_opt['R']) {
6050 		if (argc > 0) {
6051 			zopt_objects = argc;
6052 			zopt_object = calloc(zopt_objects, sizeof (uint64_t));
6053 			for (unsigned i = 0; i < zopt_objects; i++) {
6054 				errno = 0;
6055 				zopt_object[i] = strtoull(argv[i], NULL, 0);
6056 				if (zopt_object[i] == 0 && errno != 0)
6057 					fatal("bad number %s: %s",
6058 					    argv[i], strerror(errno));
6059 			}
6060 		}
6061 		if (os != NULL) {
6062 			dump_dir(os);
6063 		} else if (zopt_objects > 0 && !dump_opt['m']) {
6064 			dump_dir(spa->spa_meta_objset);
6065 		} else {
6066 			dump_zpool(spa);
6067 		}
6068 	} else {
6069 		flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
6070 		flagbits['c'] = ZDB_FLAG_CHECKSUM;
6071 		flagbits['d'] = ZDB_FLAG_DECOMPRESS;
6072 		flagbits['e'] = ZDB_FLAG_BSWAP;
6073 		flagbits['g'] = ZDB_FLAG_GBH;
6074 		flagbits['i'] = ZDB_FLAG_INDIRECT;
6075 		flagbits['p'] = ZDB_FLAG_PHYS;
6076 		flagbits['r'] = ZDB_FLAG_RAW;
6077 
6078 		for (int i = 0; i < argc; i++)
6079 			zdb_read_block(argv[i], spa);
6080 	}
6081 
6082 	if (dump_opt['k']) {
6083 		free(checkpoint_pool);
6084 		if (!target_is_spa)
6085 			free(checkpoint_target);
6086 	}
6087 
6088 	if (os != NULL)
6089 		close_objset(os, FTAG);
6090 	else
6091 		spa_close(spa, FTAG);
6092 
6093 	fuid_table_destroy();
6094 
6095 	dump_debug_buffer();
6096 
6097 	libzfs_fini(g_zfs);
6098 	kernel_fini();
6099 
6100 	return (error);
6101 }
6102