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