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