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