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