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